Search code examples
angularjsnode.jsmongodbmongoose

Get parent child data from mongodb nodejs


I am new in mongodb I am just starting mongodb with nodejs.I dont know how to get comments array. My document looks:

{
   "__v": NumberInt(0),
   "_id": ObjectId("565443b1172e19d51f98b0ed"),
   "address": "tohana",
   "comments": [
     {
       "_id": ObjectId("5654455fe088d89c20736e3c"),
       "comment": "good man",
       "uemail": "[email protected]",
       "uname": "dinesh" 
    },
     {
       "_id": ObjectId("565445e471dce6ca20705a84"),
       "comment": "nice person",
       "uemail": "[email protected]",
       "uname": "krishan" 
    },
     {
       "_id": ObjectId("5654460e7aa73bec2064060e"),
       "comment": "bad person",
       "uemail": "Rai",
       "uname": "Rahul" 
    } 
  ],
   "email": "[email protected]"▼,
   "name": "Nishant" 
}

I want to fetch comments data by id.My code is:

var Users = require("../app/models/users");// model
app.get('/commentsEdit/:id', function(req, res) {
var id = req.params.id;//here is comment id



 res.send({data:id});

})

Solution

  • var Users = require("../app/models/users");// model
    app.get('/commentsEdit/:id1/:id2', function(req, res) {
    var id1 = req.params.id1;//here is user id
    var id2 = req.params.id2;//here is comment id
    Users.find({"_id": id1}, { comments: { $elemMatch: { _id: id2 }}})
         .exec(function(err, data) {
             if(err){
               console.log(err)
            }
            else{
              console.log(data);
            }
    })