Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoosejs - Filter out populate results

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);
like image 927
Kay Avatar asked Sep 24 '17 15:09

Kay


People also ask

How does populate work in Mongoose?

Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

What is populate method in MongoDB?

populate() function in mongoose is used for populating the data inside the reference. In your example StorySchema is having _creator field which will reference to the _id field which is basically the ObjectId of the mongodb document. populate() function can accept a string or an object as an input.

What is populate in node JS?

populate() Modify a query instance so that, when executed, it will populate child records for the specified collection, optionally filtering by subcriteria . Populate may be called more than once on the same query, as long as each call is for a different association. .populate(association, subcriteria)


1 Answers

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) { });
like image 121
barnski Avatar answered Sep 23 '22 13:09

barnski