Reputation: 92745
My application has three collections Users, Channels and Feeds in MongoDB
Users can be registered for Channels. so Channel will have bunch of reference ID of user who has registered for that Channel.
Channel has multiple feeds. Feed document has reference ID to channel.
I want to retrieve the User Feeds based the channel he is subscribed. How do i achieve this in Mongoose?
Upvotes: 2
Views: 2267
Reputation: 13821
You can use the ObjectId
schema type to reference documents in other collections. And then you can use populate
to populate those documents when you query the parent document. For instance:
var UserSchema = new Schema({
// Some fields
channels: [{type: ObjectId, ref: 'Channel'}]
});
Then when you fetch a user, you can use populate
like this:
User.findById(user._id).populate('channels').exec(function(err, userWithChannels) {
var channels = userWithChannels.channels;
// Do your work
});
You should be able to reverse the relation if that's what you want instead.
Upvotes: 6