大家。我想保存多层次的JSON文档,例如,我有一个嵌套的JSON,其元素级别如下:
{
"created":"2015-11-10 15:47:41.107Z",
"id_user" : "01",
"version" : "1"
"record" : {
"name" : "Carl Powers",
"reference" : [{ "url" : "www.test.com", "created" : "2015-11-10 15:47:41.107Z"}]
}
}
我想保存这个JSON,为每个元素使用不同的Schema,因为我想在MongoDB中使用不同的集合,我不想要一个带有嵌入元素的模式。
var ElementSchema = new Schema({
created : {type: Date, default: Date.now},
id_user : String,
version : { type: Number, min: 0 },
record : {type: Schema.Types.ObjectId, ref: 'recordSchema'}
});
var recordSchema = new Schema({
name : String,
reference : [{type: Schema.Types.ObjectId, ref: 'referenceSchema'}]
});
var referenceSchema = new Schema({
url : String,
created : {type: Date, default: Date.now}
});
可以使用mongoose一次性完全保存我的示例JSON。有必要把每个元素的ID?在这种情况下,一旦收到JSON,生成每个id以及如何放入每个元素的最佳方法是什么?
答案 0 :(得分:0)
这可以使用子文档来解决,这里是一个例子:
var referenceSchema = new Schema({
url : String,
created : {type: Date, default: Date.now}
});
var recordSchema = new Schema({
name : String,
reference : [referenceSchema]
});
var ElementSchema = new Schema({
created : {type: Date, default: Date.now},
id_user : String,
version : { type: Number, min: 0 },
record : recordSchema
});
使用子文档保存Element文档:
var element = new ElementSchema({
created: 'date',
id_user: 'user-id',
version: 2
record: {
name: 'name',
reference: [{
url: 'url1',
created: 'date1'
}, {
url: 'url2',
created: 'date2'
}]
}
});
Here's the documentation for more queries for sub-documents: