目前我正在尝试执行以下操作:
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);
但我刚刚收到以下错误:
类型错误:ItemSchema.find 不是函数
如何在 post('save') 中间件中调用 .find() 方法? (我知道,Schmemas 有一个独特的属性。如果名称字符串已经存在,我必须这样做以添加后缀)
猫鼬版本:5.1.3 节点版本: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,Promise.reject
也是如此。
我们可以先声明模型名称,然后用它通过名称获取模型实例,然后就可以使用模型的静态函数了。例如:查找、findOne ...等
const modelName = 'Item'; // <---- Hint
const ItemSchema = mongoose.Schema({
...
name : String
...
});
ItemSchema.pre(
'save',
{ document: 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);