简体   繁体   English

猫鼬在Ref模式中保存对象数组

[英]Mongoose save an array of objects in Ref schema

I've got the Parent Schema: 我有Parent模式:

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

And this is the Children Schema: 这是Children模式:

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

I have an incoming user register POST request in the following format: 我有以下格式的传入用户注册POST请求:

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

Here's the router: 这是路由器:

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

This results in the following error: 这将导致以下错误:

Cast to Array failed for value "[ { name: 'test', surname: 'test' } ]" at path "children"

How can I save all children and keep in the ref only the children _id so i can later populate the Parent collection? 如何保存所有children并仅在子代_id保留ref ,以便以后populateParent集合?

The children field in the parent is expecting an arrays of ObjectIds but you are passing it an arrays of objects that do not conform to that expectation. 父项中的children字段需要一个ObjectIds数组,但是您要传递给它一个不符合该期望的对象数组。 Please try saving the children, getting the ids and then using those ids to populate the children field in parent document. 请尝试保存子代,获取ID,然后使用这些ID填充父文档中的子代字段。 Something like below: 如下所示:

 children.save() .then(results => { childrenids = [] results.foreach[item => childrenids.push(result._id)] newParent.children = chilrenids newParent.save() .then(results => res.send({results}) }) 

To save childData in Parents, You need to save first child's data in children schema Then get childIds and save to Parent Data. 要将childData保存在Parents中,您需要将第一个孩子的数据保存在children模式中,然后获取childIds并保存到Parent Data中。

Working Example: 工作示例:

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);
      })
    }
  });

Note : 注意 :

Test on "mongoose": "^5.3.3" 测试"mongoose": "^5.3.3"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM