Insert a sub-document into a Mongoose sub-document

-1

I currently have an object like this:

{
  _id: 5ab5051ec97a4202984f2973,
  student_code: "1234567890",
  name: "myname",
  lastname: "mylastname",
  areas: []
}

With mongoose I can insert a sub-document in areas like this:

.post(function(req,res){
  Imagen.findById(req.params.id, function(err,imagen){
     res.locals.imagen.areas.push({
           area: req.body.area, //Objeto a insertar
           dependencies: [] //Array para después insertar sub-documents
     });
     res.locals.imagen.save(function(err){
        if(!err){
           res.render("app/imagenes/show",{imagen:imagen});
           console.log()
        }else{
           res.render("app/imagenes/"+imagen.id+"/edit",{imagen:imagen});
           console.log(err)
        }
     })
   })
})

I search for the object that I need using Imagen.findById , then I choose the array to which I am going to pass the sub-document using res.locals.imagen.areas.push and at the end of the insertion of the sub-document I have something like this:

{
  _id: 5ab5051ec97a4202984f2973,
  student_code: "1234567890",
  name: "myname",
  lastname: "mylastname",
  areas: [
           {
            _id: 5a1d53a2e8612902034c17a0
            area: "myarea", 
            dependencies: [] //Aquí quiero insertar sub-documentos
           },
           {
            _id: 5a1d53a2e8612302034c17b9
            area: "myareax", 
            dependencies: [] //Aquí quiero insertar sub-documentos
           }...
         ] 
}

My question is: how can I insert sub-documents in the array dependencies by choosing an object of areas by _id ?

That is: how do I do when I want to insert a sub-document into the array dependencies of the object that has the _id 5a1d53a2e8612902034c17a0 if I do not know the location of the object within the array areas ?

in advance I appreciate the help you can offer me.

    
asked by Michael Valdes Gonzalez 23.03.2018 в 15:23
source

1 answer

0

The correct way to insert the sub document looking for the object by the _id is:

 .post(function(req,res){
    Imagen.findById(req.params.id, function(err,imagen){
       res.locals.imagen.areas.id(_id /*pasar el id del objeto*/).dependencies.push({
         //objeto a insertar
    });
    res.locals.imagen.save(function(err){
       if(!err){
          res.render("app/imagenes/show",{imagen:imagen});
          console.log()
       }else{
          res.render("app/imagenes/"+imagen.id+"/edit",{imagen:imagen});
          console.log(err)
       }
    })
  })
})
    
answered by 05.04.2018 / 15:14
source