繁体   English   中英

如何使用Mongoose更新具有未知数量可能字段的MongoDB集合

[英]How to update a MongoDB collections with an unknown number of possible fields using Mongoose

我想更新mongodb集合,而又不确切知道将使用多少和哪些字段进行更新。 例如,如果我有一个用户,并且他们在不同的页面上更新了有关他们的信息,那么它将不会总是与更新的字段相同。

以下是我目前的解决方法,但我愿意接受其他选择。

app.post("/user", (req, res) => {
  console.log(req.body);
  // req.body can consist of 1 or more of the following { FirstName, LastName, Email, Interests, UserRole }
  const CreatedAt = Date.now();

  if (req.body.Name) {
    let promise = User.findOne({ Name: req.body.Name });
      promise.then(user => {
        for (let key in req.body) {
          // Name will print but nothing else, nothing is updated either and there are no errors
          console.log(key);
          User
            .where({_id: user._id })
            .setOptions({ multi: true })
            .update({ $set: { [key]: key } })
            .update({ $set: { UpdatedAt: Date.now() } })
            .catch(err => res.json({message:"Failed to update the database."}));
        }
      }).catch(err => res.json({message:"User could not be found."}));

  } else {
     res.json({message:"Please provide an email and a password."});
  };
});

这里最大的问题是,我不知道将更新哪个或哪些字段,并且如果要检查以下每个可能值是否可用,我也不想花很长时间。

根据文档,您可以更改字段并保存:

app.post("/user", (req, res) => {
  console.log(req.body);
  //req.body can consist of 1 or more of the following 
  //  { FirstName, LastName, Email, Interests, UserRole }
  const CreatedAt = Date.now();

  if (req.body.Name) {
    User.findOne({ Name: req.body.Name })
    .then(user => {
      //mutate user:
      Object.keys(req.body).reduce(
        (user,key)=>{
          user[key]=req.body[key];
          return user;
        }
        ,user
      );
      //set UpdatedAt
      user.UpdatedAt = Date.now();
      //http://mongoosejs.com/docs/documents.html
      //  maybe outdated, does not mention promise but
      //  you could try return user.save()
      return new Promise(
        (resolve,reject)=>
          user.save(
            (err,user)=>
              (err)
                ? reject(err)
                : resolve(user)
          )
      )
    })
    .then(user=>res.json({message:user}))
    .catch(err => res.json({message:"User could not be found."}));
  } else {
    res.json({message:"Please provide an email and a password."});
  };
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM