我只想更新那些字段,我已传递其他数据的那些键应该保持不变,但在我的情况下,我已传递的更改其他键的键设置为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/