i want to create 1 objects nested document like:
我想创建1个对象嵌套文档,如:
Children:
儿童:
chil1:
chil1:
{ name: 'Mimi',
parent: 537258f63eb92b3201b65e56,
_id: 537258f63eb92b3201b65e57,
__v: 0 },
chil2
chil2
{ name: 'Kiki',
parent: 537258f63eb92b3201b65e56,
_id: 537258f63eb92b3201b65e58,
__v: 0 }
Parent:(What i want)
家长:(我想要的)
[ { 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 } ]
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:
有可能用nodejs(express)在mongooese上创建数据吗?它类似于这个问题mongoose:如何插入单个子文档 - 不是数组但在这种情况下,子节点只存储了子节点的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',
}],
});
Normally result :
通常结果:
{ name: 'John',
_id: 537258f63eb92b3201b65e56,
__v: 0,
children: [Chil1_id, Chil2_id]
}
1 个解决方案
#1
2
Did you try populate?
你尝试过填充吗?
Here is a simple example:
这是一个简单的例子:
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.
只要您指定孩子对模型的引用,猫鼬就足够聪明,可以将孩子与父母一起加入。
#1
2
Did you try populate?
你尝试过填充吗?
Here is a simple example:
这是一个简单的例子:
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.
只要您指定孩子对模型的引用,猫鼬就足够聪明,可以将孩子与父母一起加入。