Mongoose “this.model is not a function”

余生颓废 提交于 2020-01-24 20:08:37

问题


This is how I defined my Schema & Schema methods.

 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);

adding items to the database and using the methods.

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");
            });

        });

    });

});

The console.log(mouse) prints the first mouse document it found

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

Yet I am getting an error that this.models is not a function.

this.model is not a function.
at model.ItemSchema.methods.brandFind >(/Users/sean/ApplicationsDevelopment/sandbox.js:39:21)


回答1:


You defined 'model' as string when you create new Schema. Just delete model:String,

http://mongoosejs.com/docs/models.html



来源:https://stackoverflow.com/questions/45557696/mongoose-this-model-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!