gpt4 book ai didi

node.js - Mongoose 在 Ref 模式中保存对象数组

转载 作者:太空宇宙 更新时间:2023-11-04 01:41:26 24 4
gpt4 key购买 nike

我有架构:

const parentSchema = new Schema({
name: {
type: String,
},
children: [{
type: Schema.Types.ObjectId,
ref: "Children"
}]
})

这是Children架构:

const childrenSchema = Schema({
name: {
type: String
},
surname: {
type: String
}
})

我有一个传入的用户注册 POST 请求,格式如下:

{
"name": "TEST",
"children" : [
{ "name":"test","surname": "test" },
{ "name":"test","surname": "test" }
]
}

这是路由器:

 router.post("/register", (req, res, next) => {
const {name, children} = req.body;
let newParent = newParent({
name,
children
});
newParent.save((err, result) => {
// res.send(result) etc.
})
}

这会导致以下错误:

路径“children”处的值“[ { name: 'test', surname: 'test' } ]”转换为数组失败

如何保存所有子项并仅将子项_id保留在ref中,以便稍后可以填充Parent集合?

最佳答案

To save childData in Parents, You need to save first child's data in children schema Then get childIds and save to Parent Data.

工作示例:

let req = {
"name" : "TEST",
"children" : [
{ "name":"test","surname": "test" },
{ "name":"test","surname": "test" }
]
}

Children.collection.insert(req.children, function (err, docs) {
if (err){
conasolw.log(err);
} else {
var ids = docs.ops.map(doc=>{ return doc._id});;
console.log(ids);
let newParent = Parent({
name : req.name,
children : ids
});
newParent.save((err, result) => {
console.log('parent save');
console.log(err);
console.log(result);
})
}
});

注意:

Test on "mongoose": "^5.3.3"

关于node.js - Mongoose 在 Ref 模式中保存对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52779692/

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