Mongoose: Exclude objects from results based on another model

424
May 01, 2017, at 07:31 AM

Let's say I have a User and Group model, groups have users, like

var GroupSchema = mongoose.Schema({
    name: String,
    users: [{ type: mongoose.Schema.ObjectId, ref: 'User' }]
});

How would I query to get all the Users but exclude the ones that are on Group.users, I'm already doing this by querying first Group then manually filtering against all users

        var groupP = Group.findById(group_id).populate('users');
        var userP = User.find();
        Promise.props({
            group: groupPromise.exec(),
            users: usersPromise.exec()
        })
        .then(function (result) {
        //this gives the expected result but I'm looking for a more straight forward mongoose only solution if possible
          var users = differenceWith(result.users, result.group.users, (a, b) => { return a._id.toString() == b._id.toString()});
        })
Answer 1

You can try below query.

var groupP = Group.findById(group_id);
var userP = User.find({_id:{$nin:groupP.users}});
READ ALSO
What to use in NodeJS to create process which works long time and is accessible during its lifetime

What to use in NodeJS to create process which works long time and is accessible during its lifetime

I want to create some process which will work for a long time and it will be possible to obtain data from this process by get request

282
Routing in ReactJS

Routing in ReactJS

Can anyone explain to me how Routing works in Reactjs?

469
How to use rest api in client side?

How to use rest api in client side?

Hello today I have simple code Nodejs express that work as rest apiIt work when i use postman to send request as get method like code below

451