-2

I have two collection - Call them main and sub. My main collection looks like below,

{
  "_id" : "xxxxx",
  "subId" : "1234"
}

And my sub looks something like,

{
  "_id" : "1234",
  "name" : "somename"
}

And I write a query like -

Main.find({_id : { $in : ids }},function(err, results){
  //Do something here
});

Now, I want my final result as,

{
  "_id" : "xxxx",
  "subName" : "somename"
}

How do I iterate in the documents and achieve the desired result. i am fairly new to MEAN stack. Any help would be appreciated. Thanks in advance.

Manjunath Singh
  • 95
  • 3
  • 10

1 Answers1

1

You could use reference and populate schemas like these:

var mainSchema = Schema({
  _id: Number,
  subId: Number,
  name: [{ type: Schema.Types.ObjectId, ref: 'Sub' }]
});

var subSchema = Schema({
  _id: Number,
  name: String,
});

var Main  = mongoose.model('Main', mainSchema);
var Sub = mongoose.model('Sub', subSchema);

Now you can "populate" the query with the subdocuments from Sub collection:

Main.find({_id : { $in : ids }}).populate('name').exec(function(err, results){
  //Do something here
});
michelem
  • 14,430
  • 5
  • 50
  • 66