gpt4 book ai didi

node.js - 创建在 Mongoose 中嵌套子对象的对象父对象

转载 作者:可可西里 更新时间:2023-11-01 10:21:45 26 4
gpt4 key购买 nike

我想创建 1 个对象嵌套文档,如:

children :

child 1:

{ name: 'Mimi',                                                                                                                                                                                                                            
parent: 537258f63eb92b3201b65e56,
_id: 537258f63eb92b3201b65e57,
__v: 0 },

child 2

{ 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但在这种情况下, child 只存储 child 的 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]
}

最佳答案

你试过了吗populate

这是一个简单的例子:

Parent.find().populate("children").exec(...)

只要您指定 child 对模型的引用, Mongoose 就足够聪明,可以将 child 与 parent 联系起来。

关于node.js - 创建在 Mongoose 中嵌套子对象的对象父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38820071/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com