Javascript 如何使用新对象更新我的DB文档?

Javascript 如何使用新对象更新我的DB文档?,javascript,express,Javascript,Express,我试图通过添加firstName和lastName来更新我的DB文档,但当我使用我的函数时,它实际上覆盖了所有内容。例如,我的对象现在看起来像这样 { "_id" : ObjectId("5b0df225287cc77612ed89a5"), "email" : "user@user.com", "password" : "$2HbyP4.ts9O/zrjV5Pcd/Z28bhOb8oGas9wEG", "userData" : [ {

我试图通过添加
firstName
lastName
来更新我的DB文档,但当我使用我的函数时,它实际上覆盖了所有内容。例如,我的对象现在看起来像这样

{
    "_id" : ObjectId("5b0df225287cc77612ed89a5"),
    "email" : "user@user.com",
    "password" : "$2HbyP4.ts9O/zrjV5Pcd/Z28bhOb8oGas9wEG",
    "userData" : [ 
        {
            "role" : "user",
            "phone" : 747483245,
            "_id" : ObjectId("5b0df225287cc77612ed89a6"),
            "address" : [ 
                {
                    "_id" : ObjectId("5b0df225287cc77612ed89a7")
                }
            ]
        }
    ],
    "__v" : 0
}
但当我更新时,它看起来是这样的

{
    "_id" : ObjectId("5b0df225287cc77612ed89a5"),
    "email" : "user@user.com",
    "password" : "$2HbyP4.ts9O/zrjV5Pcd/Z28bhOb8oGas9wEG",
    "userData" : [ 
        {
            "firstName" : "First Name",
            "lastName" : "Last Name",
            "_id" : ObjectId("5b0df225287cc77612ed89a6"),
            "address" : [ 
                {
                    "_id" : ObjectId("5b0df225287cc77612ed89a7")
                }
            ]
        }
    ],
    "__v" : 0
}
所以我不再有
角色
手机
这是我的功能

// Update user data
exports.update = function (req, res, next) {
  User.findByIdAndUpdate(req.user._id, req.body)
    .exec()
    .then(doc => res.json(doc))
    .catch(err => res.json(err))
}
试着这样做:

exports.update = function (req, res) {
  User.findByIdAndUpdate(req.user._id, { $set: { firstName: req.body.firstName , lastName:req.body.lastName }}, {upsert:true},function(err,user){
        if(err){
            res.json(err);
        }else{
            res.json(user);
       }
   }
}
试试这个

exports.update = (req, res) => {

  const query = {_id: req.user._id},
    update = { $set: {
       "userData.$.firstName": req.body.firstName, 
       "userData.$.lastName": req.body.lastName }
    },
    options = { upsert:true };

  User.findByIdAndUpdate(query, update, options)
    .exec()
    .then(user => res.json(user))
    .catch(err => res.json(err));
}

即使这样,也在做同样的事情。我想更新已经插入的对象,如果没有,则插入新对象,但不删除现有对象和新对象untouched@SaurabhMistry它仍在删除旧元素“errmsg”:“异常:位置运算符未从查询中找到所需的匹配项。未展开的更新:userData.$.lastName”