【问题标题】:Mongoose "this.model is not a function"猫鼬“this.model 不是函数”
【发布时间】:2018-01-15 09:30:57
【问题描述】:

这就是我定义架构和架构方法的方式。

 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)

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    您在创建新架构时将“模型”定义为字符串。 只需删除model:String,

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

    【讨论】:

    • 让我免于头疼。谢谢!
    猜你喜欢
    • 2019-01-18
    • 2021-07-14
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    • 2019-10-05
    • 1970-01-01
    相关资源
    最近更新 更多