【问题标题】:Update a document returned by findOne()/find()/findById() - mongoose更新 findOne()/find()/findById() 返回的文档 - mongoose
【发布时间】:2020-05-13 17:39:48
【问题描述】:

我想知道是否有任何方法可以更改 mongoose find()findOne()findById() 方法返回的文档对象的可用字段的值,并使用应用于数据库的更改来更新它们。下面的代码 sn-p 是我期望完成我想要的工作:

User.findOne({ email: email })
      .then(user => {
        if (user) {
            user.fieldToUpdate = "Updated value"; // Here I'm getting the field and updating it with the new value;
            user.save().then().catch(); // Here I'm updating the document to the database, expecting for a promise object
        } else {
          const error = new Error("No such user in the database.");
          error.httpStatusCode = 422;
          next(error);
        }
      })
      .catch(error => {
        next(error);
      });

【问题讨论】:

标签: node.js mongoose


【解决方案1】:

您编写的代码 sn-p 可以正常工作,但如果您只需要更新找到的文档:

User.findOneAndUpdate({ email }, { email: 'sample@test.com' })
  .then((err, user) => {
    //
  }

More on the Docs

【讨论】:

  • 谢谢!我认为使用 findOneAndUpdate() 更方便。
猜你喜欢
  • 1970-01-01
  • 2019-07-15
  • 2013-12-04
  • 2020-11-12
  • 2018-06-09
  • 2019-03-19
  • 2019-07-14
  • 2013-01-17
  • 2018-02-27
相关资源
最近更新 更多