MongoDB, update collection field if new value is not null

前端 未结 8 833
感情败类
感情败类 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:18

    You can use mongoose for that by casting req.body to your model,

    I assume you have mongoose model called User, and in your controller,

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

    There is no mongoose tag, but I strongly recomment to use that. For more details;

    Mongoose Update

    Mongoose Model

提交回复
热议问题