MongoDB, update collection field if new value is not null

前端 未结 8 827
感情败类
感情败类 2020-12-29 13:45

I would update a collection setting the value only if the new values are not null. I have a code like this:

 ...
 var userName = req.body.nome;
 var userSurn         


        
8条回答
  •  鱼传尺愫
    2020-12-29 14:07

    The answer by Hüseyin BABAL is on the right track, but that will generate a warning from mongo because calling new User() will create a new _id which is immutable. What you want to do is the following:

    const userModel = Object.assign(req.body);
    User.update({_id: req.session.userID}, userModel, {upsert: true}, 
      function(err){
        console.log("Error occured!");
      });
    

提交回复
热议问题