gpt4 book ai didi

node.js - 我想更新用户个人资料

转载 作者:太空宇宙 更新时间:2023-11-04 03:15:48 25 4
gpt4 key购买 nike

我只想更新那些字段,我传递的其他数据的键应该保持不变,但在我的情况下,我传递的更改其他数据的键设置为 null

import userModel from '../../models/usermodel'
import {Request,Response} from 'express'
import jwt from 'jsonwebtoken'

const editprofile = (req:Request,res:Response)=>{

let newData = new userModel(req.body)

const userObj = {
email: req.body.email || null,
first_name: req.body.first_name || null,
last_name: req.body.last_name || null,
dob: req.body.dob || null,
phone: req.body.phone || null,
gender: req.body.gender || null,
// profile_img: req.file.filename || null
};

userModel.findByIdAndUpdate({'_id':req.body._id}, { $set: userObj }, { upsert: true, new: true })

.then(result=>{
res.status(200).json({success:true,message:"Profile Updated",customer:result})
console.log('result',result)
})
.catch(err=>{
res.status(404).json({success:false,message:"Something went wrong",error_message:err})
})
}
export default editprofile

最佳答案

您可以使用循环来填充给定字段:

  let newObj = {};
Object.keys(req.body).forEach(function(prop) {
newObj[prop] = req.body[prop];
});

或者

使用 findOne() 来获取记录字段:

  let query = { $set: {} };
for (let key in req.body) {
if (customer[key] && customer[key] !== req.body[key])// if the field we have in req.body exists, we're gonna update it
query.$set[key] = req.body[key];
}

关于node.js - 我想更新用户个人资料,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56526295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com