我想创建1个对象嵌套文档,如:
儿童:
chil1:
{ name: 'Mimi',
parent: 537258f63eb92b3201b65e56,
_id: 537258f63eb92b3201b65e57,
__v: 0 },
chil2
{ name: 'Kiki',
parent: 537258f63eb92b3201b65e56,
_id: 537258f63eb92b3201b65e58,
__v: 0 }
父母:(我想要的)
[ { name: 'John',
_id: 537258f63eb92b3201b65e56,
__v: 0,
children: [ { name: 'Mimi',
parent: 537258f63eb92b3201b65e56,
_id: 537258f63eb92b3201b65e57,
__v: 0 },
Children:[ { name: 'Mimi',
parent: 537258f63eb92b3201b65e56,
_id: 537258f63eb92b3201b65e57,
__v: 0 },
{ name: 'Kiki',
parent: 537258f63eb92b3201b65e56,
_id: 537258f63eb92b3201b65e58,
__v: 0 } ]
可以用nodejs(express)在mongooese上创建数据吗? 它类似于这个问题mongoose: How to insert a single subdocument - not an array 但在这种情况下,孩子们只存储了孩子的id,而不是所有的对象? 这是我的模型文件:
const schema:mongoose.Schema = new mongoose.Schema({
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},
name: String,
parentCategory: {
type: mongoose.Schema.Types.ObjectId,
ref: 'parent',
},
childCategories: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'child',
}],
});
通常结果:
{ name: 'John',
_id: 537258f63eb92b3201b65e56,
__v: 0,
children: [Chil1_id, Chil2_id]
}
答案 0 :(得分:2)
您是否尝试过populate?
这是一个简单的例子:
Parent.find().populate("children").exec(...)
只要您指定孩子对模型的引用,猫鼬就足够聪明,可以将孩子与父母一起加入。