Mongoose TypeError:Object {}没有方法'cast'

时间:2015-02-24 13:13:32

标签: node.js mongodb mongoose

我试图将对象推入Mongoose数组,但是收到以下错误:

TypeError: Object {} has no method 'cast'
at Array.MongooseArray._cast (/vagrant/kernl/node_modules/mongoose/lib/types/array.js:108:30)
at Object.map (native)
at Array.MongooseArray.push (/vagrant/kernl/node_modules/mongoose/lib/types/array.js:262:23)
at Promise.<anonymous> (/vagrant/kernl/routes/plugins.js:128:41)
at Promise.<anonymous> (/vagrant/kernl/node_modules/mongoose/node_modules/mpromise/lib/promise.js:177:8)
at Promise.EventEmitter.emit (events.js:98:17)
at Promise.emit (/vagrant/kernl/node_modules/mongoose/node_modules/mpromise/lib/promise.js:84:38)
at Promise.fulfill (/vagrant/kernl/node_modules/mongoose/node_modules/mpromise/lib/promise.js:97:20)
at handleSave (/vagrant/kernl/node_modules/mongoose/lib/model.js:133:13)
at /vagrant/kernl/node_modules/mongoose/lib/utils.js:408:16

架构(插件)

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    PluginVersion = require('./PluginVersion');

var PluginSchema = new Schema({
    name: { type: String, required: true },
    description: { type: String },
    created_date: { type: Date, default: Date.now },
    active: { type: Boolean, default: true },
    user: { type: Schema.Types.ObjectId, ref: 'User' },
    versions: [PluginVersion]
});

module.exports = mongoose.model('Plugin', PluginSchema);

架构(PluginVersion)

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var PluginVersionSchema = new Schema({
    version: { type: String, required: true },
    downloads: { type: Number, default: 0 },
    size: { type: Number, required: true },
    updatedChecks: { type: Number, default: 0 },
    fileName: { type: String, required: true }
});

module.exports = mongoose.model('PluginVersion', PluginVersionSchema);

发生错误的代码

var file = req.files.file,
    version = new PluginVersion();
    version.version = req.body.version;
    version.size = file.size;
    version.fileName = file.path;

    version.save(function(err) {
        if(err) { res.send(err); }
        plugin.versions.push(version); // <---- Problem.
        plugin.save(function(err) {
            if(err) { res.send(err); }
                res.status(201);
                res.json(version);
            });
         });
    });

我使用Mongoose很新,所以我的知识可能只是差距。还有一个类似的问题,但它引用了使用模式定义而不是模型定义的需要,我认为我已经正确地做了。

1 个答案:

答案 0 :(得分:5)

将一个架构嵌入另一个架构时,可以使用其架构而不是模型指定嵌入式类型。因此,PluginSchema应该像这样定义versions字段:

var PluginSchema = new Schema({
    name: { type: String, required: true },
    description: { type: String },
    created_date: { type: Date, default: Date.now },
    active: { type: Boolean, default: true },
    user: { type: Schema.Types.ObjectId, ref: 'User' },
    versions: [PluginVersion.schema]
});