从mongodb nodejs获取父子数据

时间:2015-11-25 06:26:56

标签: angularjs node.js mongodb mongoose

我是mongodb的新手我刚刚使用nodejs启动mongodb。我不知道如何获取comments数组。我的文档看起来:

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

我想通过id获取评论数据。我的代码是:

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

})

1 个答案:

答案 0 :(得分:2)

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