提问者:小点点

Mongoose pre save hook:在字段赋值之前调用next()


在深入研究这个问题之前,我知道next()将在异步操作完成运行之前被调用。但是简单的对象属性赋值不是异步的,我不确定为什么在赋值之前调用next()。还要注意的是,我已经尝试了这个程序的多个版本。

我试图仅在创建新文档时才在模型上设置weeknum属性。下面是我当前的代码:

Schema.pre('save', async function (next) {
  if (this.isNew) {
    await this.constructor.countDocuments({ type: `${this.type}` }, function (err, count) {
      if (err) {
        console.log(err)
      } else {
        this.weekNum = count + 1;
        console.log(this.weekNum); // this returns the correct variable in my console
        next(); // when I request the created document, it has no weekNum property. 
      }
    });
  }
  else {
    next();
  }
});

我还尝试将next()移动到await语句的外部和紧接其后。但是,next()似乎从不等待这个操作完成。如何确保在字段更新之前不保存文档?


共1个答案

匿名用户

我明白了--原来我把异步/等待和回调混合在一起了。下面是一个正确的方法:

Schema.pre('save', async function (next) {
  try {
    if (this.isNew) {
      const count = await this.constructor.countDocuments({ type: `${this.type}` })
      this.weekNum = count + 1;
      console.log(this.weekNum);
      next();
    }
    else {
      next();
    }
  }
  catch(err) {
    console.log(err);
    next();
  }
});