简体   繁体   中英

Mongoose save an array of objects in Ref schema

I've got the Parent Schema:

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

And this is the Children Schema:

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

I have an incoming user register POST request in the following format:

{
 "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?

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. Please try saving the children, getting the ids and then using those ids to populate the children field in parent document. 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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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