Mongoosejs - Filter out populate results
Asked Answered
G

3

8

I want to return all chat conversations, where the logged in user (user_id) is a participant.

I want to populate the participants only returning the profile.firstname (maybe some other later), i then want to filter out the participants so that it does not bring back the loggedInUser (user_id) in the participants array.

chat.controller.js INDEX

 Chat.find({participants: user_id})
            .populate('participants', {
                select: 'profile.firstname',
                where('_id').ne(user_id) // This need to change
            })
            .exec(function (err, chats) { });

chat.model.js

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

let ChatSchema = new Schema({

        participants: [{
            type: Schema.Types.ObjectId, ref: 'User'
        }],

        messages: [{
            type: Schema.Types.ObjectId, ref: 'Message'
        }],

    },
    {
        timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}
    });

module.exports = mongoose.model('Chat', ChatSchema);
Godolphin answered 24/9, 2017 at 15:20 Comment(0)
P
15

According to populate documentation this could be achieved by "match" option.

In your case answer would be:

Chat.find({participants: user_id})
        .populate('participants', {
            select: 'profile.firstname',
            match: { _id: {$ne: user_id}}
        })
        .exec(function (err, chats) { });
Physics answered 24/9, 2017 at 18:49 Comment(0)
J
1

The mongoose populate() documentation has a few changes. The solution should be

Chat.find({
        participants: user_id
    })
    .populate({
        path: 'participants'
        select: 'profile.firstname',
        match: {
            _id: {
                $ne: user_id
            }
        }
    })
    .exec(function(err, chats) {});
Jap answered 2/6, 2020 at 19:41 Comment(0)
C
1

With $in this code will be useful.

ServiceCategory.find().populate({
    path: "services",
    match: { zipCodes: {$in: "10400"}},
    populate: [
        {
            path: "offers",
        },
    ],
});
Caseworm answered 14/8, 2021 at 11:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.