首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >mongoose在一个pre('save')钩子中调用.find

mongoose在一个pre('save')钩子中调用.find
EN

Stack Overflow用户
提问于 2018-06-07 19:33:08
回答 1查看 1.5K关注 0票数 2

目前我正在尝试做以下几件事:

代码语言:javascript
复制
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上有一个独特的属性。我必须这样做,如果名称字符串已经存在,则必须为其添加后缀)

mongoose版本: 5.1.3 nodejs版本: 8.1.1系统: ubuntu 16.04

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-07 19:47:09

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

它应该是:

代码语言:javascript
复制
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;

或者:

代码语言:javascript
复制
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,Promise.reject也是如此。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50740145

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档