猫鼬在 pre('save') 钩子中调用 .find

sam*_*yst 2 mongoose node.js mongoose-schema

目前我正在尝试执行以下操作:

const ItemSchema = mongoose.Schema({
 ...
 name : String
 ...
});

ItemSchema.pre('save', async function() {
  try{
     let count = await ItemSchema.find({name : item.name}).count().exec();
     ....
     return Promise.resolve();
  }catch(err){
     return Promise.reject(err)
  }
});

module.exports = mongoose.model('Item', ItemSchema);
Run Code Online (Sandbox Code Playgroud)

但我只是收到以下错误:

类型错误:ItemSchema.find 不是函数

如何在我的 post('save') 中间件中调用 .find() 方法?(我知道,Schmemas 上有一个独特的属性。如果名称字符串已经存在,我必须以这种方式对其进行后缀)

猫鼬版本:5.1.3 nodejs 版本:8.1.1 系统:ubuntu 16.04

Est*_*ask 8

find静态方法在模型上可用,而ItemSchema模式是可用的。

它应该是:

ItemSchema.pre('save', async function() {
  try{
     let count = await Item.find({name : item.name}).count().exec();
     ....
  }catch(err){
     throw err;
  }
});

const Item = mongoose.model('Item', ItemSchema);
module.exports = Item;
Run Code Online (Sandbox Code Playgroud)

或者:

ItemSchema.pre('save', async function() {
  try{
     const Item = this.constructor;
     let count = await Item.find({name : item.name}).count().exec();
     ....
  }catch(err){
         throw err;
  }
});

module.exports = mongoose.model('Item', ItemSchema);
Run Code Online (Sandbox Code Playgroud)

请注意,它Promise.resolve()async功能上是多余的,它已经在成功的情况下返回已解决的承诺,因此Promise.reject.