2017-08-08 63 views
1

这是我如何定义我的模式&架构方法。猫鼬“this.model是不是一个函数”

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(鼠标)打印第一个鼠标文件就可以发现

{ _id: 598907ecbf5ac40b24346028, 
    type: 'Mouse', 
    brand: 'Corsair', 
    description: '2', 
    model: 'G104', 
    price: 8000, 
} 

但我得到的是this.models不是一个函数错误。

this.model不是一个函数。
在model.ItemSchema.methods.brandFind>(/用户/肖恩/ ApplicationsDevelopment/sandbox.js:39:21)

回答