我有以下包含嵌套架构的数据:
用户架构
(function userModel() {
var mongoose = require('mongoose');
var Entry = require('./entry');
var Schema = mongoose.Schema;
var usersSchema = new Schema({
entries: [Entry]
});
module.exports = mongoose.model('Users', usersSchema);
})();
条目架构
(function entryModel() {
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var entrySchema = new Schema({
timeStamp: {
type: Date,
default: Date.now
},
data : [Schema.Types.Mixed]
});
module.exports = mongoose.model('Entry', entrySchema);
})();
我返回以下错误:
errors:
{ entries:
{ [CastError: Cast to Array failed for value "[object Object]" at path "entries"]`
据我所知,这是包含子文档的正确方法。我在这里做错什么了吗?
最佳答案
此行导出module.exports = mongoose.model('Entry', entrySchema);
而不是model
。您需要导出schema
并使用它来构造entrySchema
编辑:
如果要同时导出模型和模式,则需要执行以下操作
module.exports = {
schema: entrySchema,
model: mongoose.model('Entry', entrySchema)
}
但是,一般情况下,您很少需要导出实际模型。这是因为每当您想访问另一个文件中的特定模型时,您只需调用
userSchema
并获取该模型实例。不需要调用mongoose.model('Entry')
就可以访问模型。