目前我正在尝试做以下几件事:
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
发布于 2018-06-07 19:47:09
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,Promise.reject
也是如此。
https://stackoverflow.com/questions/50740145
复制相似问题