[英]Mongoose “this.model is not a function”
這就是我定義Schema和Schema方法的方式。
const Schema = mongoose.Schema;
const ItemSchema = new Schema({
type:String,
brand:String,
description:String,
model:String,
price:Number,
createdAt:{type: Date, default: Date.now},
updatedAt:{type: Date, default: Date.now}
});
ItemSchema.statics.findBrand = function(brand, callback){
// this == item
return this.find({brand: brand}, callback);
}
ItemSchema.statics.findType = function(type, callback){
return this.find({type: type}, callback);
}
ItemSchema.methods.findSameBrand = function(cb){
return this.model("Item").find({brand: this.brand}, cb);
}
var Item = mongoose.model("Item", ItemSchema);
將項目添加到數據庫並使用方法。
Item.remove({}, function(err) {
if (err) console.error(err);
Item.create(itemData, function(err, items) {
if(err) console.error(err);
Item.findOne( {type: "Mouse"}, function(err, mouse){
console.log(mouse);
mouse.findSameBrand( (err, items) => {
if (err) console.error(err);
//any code
db.close( () => {
console.log("connection closed");
});
});
});
});
console.log(mouse)打印找到的第一個鼠標文檔
{ _id: 598907ecbf5ac40b24346028,
type: 'Mouse',
brand: 'Corsair',
description: '2',
model: 'G104',
price: 8000,
}
但是我收到一個錯誤,說this.models不是一個函數。
this.model不是函數。
在model.ItemSchema.methods.brandFind>(/Users/sean/ApplicationsDevelopment/sandbox.js:39:21)
創建新架構時,您將“模型”定義為字符串。 只需刪除model:String,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.