Reputation: 8582
Let's say for example i have 2 collections Comments and Users.The comments include username and the comment and Users has username and avatar. When retrieving the comments i also want to display the avatars, how should i query the two collections ? My first thought was to get all the comments and then iterate though the usernames and query the user collection to get the avatars. Can i do this differently ? Using nodejs and mongoose
Upvotes: 2
Views: 6382
Reputation: 33145
Populate
is likely what you're looking for:
http://mongoosejs.com/docs/populate.html
Pasting some in here for posterity: ObjectIds can now refer to another document in a collection within our database and be populate()d when querying. An example is helpful:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var PersonSchema = new Schema({
name : String
, age : Number
, stories : [{ type: Schema.ObjectId, ref: 'Story' }]
});
var StorySchema = new Schema({
_creator : { type: Schema.ObjectId, ref: 'Person' }
, title : String
, fans : [{ type: Schema.ObjectId, ref: 'Person' }]
});
var Story = mongoose.model('Story', StorySchema);
var Person = mongoose.model('Person', PersonSchema);
Upvotes: 3
Reputation: 162
If I could comment I would as this may not be a full answer. But for me Database References and MongoDB Data Modeling and Rails are pretty good explanations on the topic in general.
But definitely what you are describing is what is discussed in the first link I sent.
Upvotes: 3