【问题标题】:How to update a MongoDB collections with an unknown number of possible fields using Mongoose如何使用 Mongoose 更新具有未知数量可能字段的 MongoDB 集合
【发布时间】:2018-06-12 15:23:57
【问题描述】:

我想更新一个 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."});
  };
});

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

【问题讨论】:

    标签: javascript node.js database mongodb mongoose


    【解决方案1】:

    根据documentation,您只需更改字段并保存即可:

    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."});
      };
    });
    

    【讨论】:

    • 非常感谢,这个答案很完美!但只是为了进一步澄清,你为什么使用reduce而不是foreach?价值不是只需要访问而不需要总结吗?我只是问,因为我从来没有真正使用过 reduce 函数,而不仅仅是组合数字或字符串?
    • @Brandon 您可以使用 reduce 来翻转任何值列表并返回一个。在这种情况下,Object.keys(req.body).forEach 也可以正常工作。
    猜你喜欢
    • 2015-10-06
    • 2021-05-21
    • 1970-01-01
    • 2021-09-18
    • 2021-07-21
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 2020-03-24
    相关资源
    最近更新 更多