node.js - 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
解决方案
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
.
推荐阅读
- android - 导航抽屉项目单击不适用于其他活动
- c# - 在 C# 中不知道发件人的情况下收听事件?
- regex - 正则表达式合并所有段落的所有行,同时保持这些段落分开
- c - C,将半字节从输入转换为十六进制
- python - 如何在不改变 LSTM-Cell 之后的图形部分的情况下逐步使用 LSTM - 即具有新状态?
- flutter - Flutter:ListView.builder 中的文本字段
- android - 如何在Android(TextView)中将带有HTML代码的双引号显示为文本?
- android - Facebook AccountKit 的 Firebase 身份验证错误
- swift - Swift:Quickblox 跟踪 startcall 并获取错误(调试)
- javascript - 这是编写方法 JavaScript 的允许方式吗?