1

I'm using relation between two collection and I have collection schema like follow.

// Room database Entry.
{
    "_id" : ObjectId("59b77082f7da4b1b3f64d927"),
    "room_id" : "c3wqqkfndg9cnmi",
    "room_name" : "bcmvnxbcnvsjkfhkjdh",
    "users" : [
        {
            "_id" : ObjectId("59b77082f7da4b1b3f64d926")
        }
    ],
    "__v" : 0
}

//User Database Entry, Related with above Room entry.
{
    "_id" : ObjectId("59b77082f7da4b1b3f64d926"),
    "user_id" : "dyr1qlrtso47vi",

    "__v" : 0
}

When I pass query for Room Find and populate the data than I found result like follow.

// Query For Room find and Populate.
room
 .findOne({ room_id: result.data.room_id })
 .populate("users._id")
 .exec(function(err, data){
  });

//Result As Follow
{
   "_id":"59b77082f7da4b1b3f64d927",
   "room_id":"c3wqqkfndg9cnmi",
   "room_name":"bcmvnxbcnvsjkfhkjdh",
   "__v":0,
   "users":[
      {
         "_id":{
            "_id":"59b77082f7da4b1b3f64d926",
            "user_id":"dyr1qlrtso47vi",
            "__v":0
         }
      }
   ]
}

My Requirement is like follow, I don't want _id as key of object. I need users object like follow.

"users":[
      {
         "_id":{
            "_id":"59b77082f7da4b1b3f64d926",
            "user_id":"dyr1qlrtso47vi",
            "__v":0
         }
      }
   ]

Should be 

"users":[
         {
            "_id":"59b77082f7da4b1b3f64d926",
            "user_id":"dyr1qlrtso47vi",
            "__v":0
         }
     ]
Gunjan Patel
  • 2,342
  • 4
  • 24
  • 45
  • try to use [project](https://docs.mongodb.com/manual/reference/operator/aggregation/project/) and [example](https://stackoverflow.com/questions/43650014/how-to-get-individual-fields-in-embedded-documents/43650072#43650072) – Hari Sep 12 '17 at 05:52
  • Buddy I'm using populate for relation between two collection. – Gunjan Patel Sep 12 '17 at 05:56
  • 1
    Nonetheless you really should be using [`$lookup`](https://docs.mongodb.com/manual/reference/operator/aggregation/sort/) where available and also understanding "why" you should be using it instead. Populate is nowhere near the same thing. Whilst you could alter the document structure once returned, the real problem here is your structure was incorrect to begin with. The room data should have the `users` array as `"users" : [ObjectId("59b77082f7da4b1b3f64d926")]`. And to do that the schema should instead be `"users": [{ type: Schema.Types.ObjectId, ref: 'User' }]`. The inner `_id` is a mistake – Neil Lunn Sep 12 '17 at 06:08

0 Answers0