MongoDB, update collection field if new value is not null

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

    This version still allows for null string fields to be respected and updated. Omitted fields would be ignored.

    const cleanedObject = Object.keys(origObject).reduce((acc, k) => {
      if (typeof origObject[k] === "undefined") return acc;
      acc[k] = origObject[k];
      return acc;
    }, {});
    
    collection.update({_id:ObjectId(req.session.userID)}, cleanedObject })
    

提交回复
热议问题