创建对象父级,将子级嵌套在猫鼬中 [英] create object parent which nested children in mongoose
本文介绍了创建对象父级,将子级嵌套在猫鼬中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建1个对象嵌套文档,例如:
i want to create 1 objects nested document like:
孩子:
儿童1:
{ 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)在蒙古文上创建数据? 与此问题类似猫鼬:如何插入单个子文档-不是数组 但是在这种情况下,孩子只存储了孩子的ID,而不是所有对象? 这是我的模型文件:
is possible to create data on mongooese with nodejs(express)? it is similar this question mongoose: How to insert a single subdocument - not an array but in this case, the children only stored id of child, not all the object ? Here is my model file:
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]
}
推荐答案
您尝试填充 ?
这是一个简单的例子:
Parent.find().populate("children").exec(...)
只要您指定孩子对模型的引用,猫鼬就足够聪明,可以将孩子与父母一起加入
As long as you specify the children's ref to a model, mongoose is smart enough to join the children with the parents.
这篇关于创建对象父级,将子级嵌套在猫鼬中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文