猫鼬"this.model不是函数" [英] Mongoose "this.model is not a function"

查看:327
本文介绍了猫鼬"this.model不是函数"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我定义架构&的方式模式方法.

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

        });

    });

});

console.log(mouse)打印找到的第一个鼠标文档

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

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

但是我收到一个错误,说this.models不是一个函数.

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

此模型不是函数.
在model.ItemSchema.methods.brandFind>(/Users/sean/ApplicationsDevelopment/sandbox.js:39:21)

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

推荐答案

在创建新架构时,您将'model'定义为字符串. 只需删除model:String,

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

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

这篇关于猫鼬"this.model不是函数"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆