如何用里面的新对象更新我的DB文档?

时间:2018-05-30 01:52:40

标签: javascript express

我尝试通过添加lastName{ "_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
}

但是当我更新它时看起来像这样

role

所以我不再拥有phone// 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)) } 这是我的功能

<script type="text/javascript">
var gAutoPrint = true;

function printDiv(){


    if (document.getElementById != null){
    var html = '<HTML>\n<HEAD>\n';
    if (document.getElementsByTagName != null){
    var headTags = document.getElementsByTagName("head");
    if (headTags.length > 0) html += headTags[0].innerHTML;
    }

    html += '\n</HE' + 'AD>\n<BODY>\n';
    var printReadyElem = document.getElementById("div_content");

    if (printReadyElem != null) html += printReadyElem.innerHTML;
    else{
    alert("Error, no contents.");
    return;
    }

    html += '\n</BO' + 'DY>\n</HT' + 'ML>';

    var printWin = window.open("","processPrint");
    printWin.document.open();
    printWin.document.write(html);
    printWin.document.close();

    if (gAutoPrint) printWin.print();
    } else alert("Browser not supported.");

}

2 个答案:

答案 0 :(得分:1)

尝试这种方式:

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);
       }
   }
}

答案 1 :(得分:0)

试试这个

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));
}