我的mongo记录是这样的:
{
"_id":{"$oid":"5550b6de437f572112a29f1a"},
"cv_count":177732,
"gender_info": {"male_count": 50, "female_count": 32}
"stability_info_list":[{"ratio":8.802558610369414e-05,"total_count":34081,"years":0},{"ratio":5.868372406912943e-05,"total_count":34081,"years":1}],
"zhineng_id":"IT Manager"
}
我写这样的架构:
var ZhinengGenderSchema = new Schema({
male_count: Number,
female_count: Number
});
var ZhinengStabilitySchema = new Schema({
ratio: Number,
total_count: Number,
years: Number
});
var ZhinengStats = new Schema({
cv_count: Number,
gender_info: ZhinengGenderSchema,
stability_info_list: [ZhinengStabilitySchema],
zhineng_id: String
})
但我得到了这个例外:
TypeError: Undefined type `undefined` at `gender_info`
Did you try nesting Schemas? You can only nest using refs or arrays.
所以mongoose
不支持嵌套模式?但我的数据库已经存在,我无法更改,那么如何定义我的模式呢?
答案 0 :(得分:1)
使用 mongoose ,您可以在Array中定义嵌套(嵌入式)模式,如下所示:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var bookSchema = new Schema({
value: { type: String }
});
var authorSchema = new Schema({
books: [bookSchema]
});
或参考
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = mongoose.Schema.Types.ObjectId;
var auhtorSchema = new Schema({
book: { type: ObjectId, ref: 'Book'}
});
您可以选择更适合您的方式
答案 1 :(得分:1)
不要为子文档创建新的架构,你应该没问题,即:
var ZhinengGenderSchema = {
male_count: Number,
female_count: Number
};
var ZhinengStabilitySchema = {
ratio: Number,
total_count: Number
years: Number
};
var ZhinengStats = new Schema({
cv_count: Number,
gender_info: ZhinengGenderSchema,
stability_info_list: [ZhinengStabilitySchema],
zhineng_id: String
})
答案 2 :(得分:0)
据我所知,这是由于目前Mongoose的限制。你不能 声明架构字段以包含单个子文档:您必须使用数组。请参阅:https://github.com/Automattic/mongoose/pull/585
您可以稍后设置正确的业务逻辑,以确保只添加一个子元素。
试试这个:
var ZhinengStats = new Schema({
cv_count: Number,
gender_info: [ZhinengGenderSchema],
stability_info_list: [ZhinengStabilitySchema],
zhineng_id: String
})
这样,每个子文档在MongoDB中都有自己的_id
(即使它不在特定的集合中)。查看更多:http://mongoosejs.com/docs/subdocs.html
你可能也喜欢这样的东西:
var ZhinengStats = new Schema({
cv_count: Number,
gender_info: [{male_count: Number, female_count: Number}],
stability_info_list: [ZhinengStabilitySchema],
zhineng_id: String
})
在这种情况下,您将架构嵌套在另一个架构中。单个gender_info
元素没有文档的尊严。