mongoose在pre('save')钩子中调用.find方法

3

目前,我正在尝试完成以下内容:

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() 方法? (我知道,模式上有一个唯一的属性。如果它已经存在,我必须这样做来给名字字符串添加后缀)
mongoose版本:5.1.3 nodejs版本:8.1.1 系统:ubuntu 16.04

1
你尝试过使用 this.find 替换 ItemSchema.find 吗? - kakashi
2个回答

10

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

注意,在async函数中,Promise.resolve()是多余的,因为它已经在成功时返回了一个已解决的promise,同样的情况也适用于Promise.reject


感谢您的通知,我是异步/等待世界的新手。 - sami_analyst

0
我们可以先声明模型名称,然后通过名称获取模型实例,接着就可以使用模型的静态函数,例如:find、findOne等。
const modelName = 'Item'; // <---- Hint
const ItemSchema = mongoose.Schema({
 ...
 name : String
 ...
});

ItemSchema.pre(
  'save',
  { ducument: true },
  async function() {
    try {
      let count = await this.model(modelName) // <-- Hint
                            .find({name : item.name})
                            .count()
                            .exec();
      
    } catch(err){
        throw err;
    }
  }
);

module.exports = mongoose.model(modelName, ItemSchema);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接