更新findOne()/ find()/ findById()返回的文档-猫鼬

时间:2020-01-28 10:17:54

标签: node.js mongoose

我想知道是否有任何方法可以更改猫鼬find()findOne()findById()方法返回的文档对象的可用字段的值,并通过更改对其进行更新应用于数据库。下面的代码段是我期望完成的工作:

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

1 个答案:

答案 0 :(得分:1)

您编写的代码片段可以正常工作,但是如果您只需要更新找到的文档,则可以:

trx_id | Opening | qty_plus | qty_minus | closing |
-------+----------+---------+-----------+---------+
1      |  1000   |   100    |     0     |   1100  |
2      |  1100   |     0    |    50     |   1050  |
3      |  1050   |    10    |     0     |   1060  |
4      |  1060   |    40    |     0     |   1100  |
5      |  1100   |     0    |   300     |    800  |

More on the Docs