首页 > 解决方案 > mongoose 在 pre('save') 钩子中调用 .find

问题描述

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

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

但我只是得到以下错误:

TypeError:ItemSchema.find 不是函数

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

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

标签: node.jsmongoosemongoose-schema

解决方案


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;

或者:

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

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


推荐阅读