Stathis Ntonas
Stathis Ntonas

Reputation: 1262

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?

Upvotes: 2

Views: 3334

Answers (2)

IftekharDani
IftekharDani

Reputation: 3729

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"

Upvotes: 1

shmit
shmit

Reputation: 2524

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

Upvotes: 1

Related Questions