MongoDB, update collection field if new value is not null

前端 未结 8 857
感情败类
感情败类 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 13:58

    Are you not just asking to pass in all the fields that you posted? Why not do this then?

    (And basically just a cut and paste of your code):

    collection.update(
        {_id: ObjectId(req.session.userID)},
        {$set: req.body }
    )
    

    Then whatever content you posted as fields is set within your update.

    Note that use of set will only overwrite, or add new fields. If you just want to replace the whole document, then remove the whole {$set: (..) } notation and just pass in req body as it's a valild object.

提交回复
热议问题