Search code examples
node.jsmongodbmongoosepopulatemongoose-populate

Mongoose find only those who have an entry in another collection


I'm trying to find entry in a collection using mongoose, but I want only entries which have an entry in another collection.

To be more specific:
I have a collection 'post'

    var postSchema = new Schemas({
    postedBy:{type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    group:{type: mongoose.Schema.Types.ObjectId, ref: 'Group'},
    postContent: String
});

a collection 'group':

    var groupSchema = new Schemas({
    name: String,
    creator:{type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    interes: String,
    public: Boolean
});

and a collection 'groupMember':

var groupMemeberSchema = new Schemas({
    group:{type: mongoose.Schema.Types.ObjectId, ref: 'Group'},
    user:{type: mongoose.Schema.Types.ObjectId, ref: 'User'}
});

What I want is to retrieve all post from groups that the user is a member in.

Something like:

    groupmembers.find({user: req.user._id}, (err, groupsThatTheUserIn) => {
        post.find(({$where: this.group EXIST_IN(groupsThatTheUserIn)}, (err, posts) => {
            res.json(posts);
    }))

})
     

But their is no exist_in() function in mongoose


Solution

  • To retrieve all post from groups that the user is a member in, you can use the aggregation framework where $lookup is at your disposal to join the related collections with a single query.

    For example, running the following aggregate operation will return the desired posts:

    groupmembers.aggregate([
        { "$match": { "user": mongoose.Types.ObjectId(req.user._id) } },
        {
            "$lookup": {
               "from": "posts",
               "localField": "group”,
               "foreignField": "group",
               "as": "posts"  
            }
        },
        {  
    ], (err, results) => res.json(results[0].posts))