小编des*_*lue的帖子

更新时获取文档的旧版本和新版本

对于我的应用程序在 MongoDB 上执行的每个操作,我希望拥有文档的旧版本和新版本,以便我可以发出两个版本的事件:

{
  type: 'UPDATE',
  before: documentBeforeUpdate,
  after: documentAfterUpdate
}
Run Code Online (Sandbox Code Playgroud)

我现在执行此操作的方法是首先发出 afindOne查询,然后执行 afindOneAndUpdate更新,但使用文档_id进行查询。因此,如果查询实际上引起了数据库的负载,我不会付出两次这个代价:

async function updateOne(query, updates) {
  const oldDocument = await this.model
    .findOne(query, null, { lean: true })
    .exec();

  if (!oldDocument) {
    return;
  }

  const newDocument = await this.model
    .findOneAndUpdate({ _id: oldDocument._id }, updates, {
      new: true,
      lean: true
    })
    .exec();

  // document vanished before it could be updated
  if (!newDocument) {
    return;
  }

  await this.emit("UPDATE", {
    before: oldDocument,
    after: newDocument,
    type: …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node-mongodb-native

7
推荐指数
1
解决办法
2680
查看次数

标签 统计

mongodb ×1

mongoose ×1

node-mongodb-native ×1