MongoDB, update collection field if new value is not null

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

    If there is not any field that you dont want users to be able to change. since this method will take any value which is not empty and update it. you can do it like this.

     const updatedFields = {};
     Object.keys(req.body).forEach(key => {
       if (!isEmpty(req.body[key])) {
         updatedFields[key] = req.body[key];
       }
     });
    YourModel.findOneAndUpdate(
          { employee_id: req.body.employee_id },
          {$set:updatedFields},
          {new:true}).then(updatedObj =>{
            console.log("updated obj:",updatedObj);
          })
    

    is empty function

        const isEmpty = value =>
      value === undefined ||
      value === null ||
      (typeof value === "object" && Object.keys(value).length === 0) ||
      (typeof value === "string" && value.trim().length === 0);
    

提交回复
热议问题