Mongoose:根据其他模型从结果中排除对象

时间:2017-04-30 18:27:03

标签: node.js mongodb mongoose

假设我有UserGroup模型,群组有用户,比如

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

我将如何查询以获取所有用户但排除所有用户 Group.users,我已经通过先查询Group然后手动过滤所有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()});
        })

1 个答案:

答案 0 :(得分:1)

您可以尝试以下查询。

var groupP = Group.findById(group_id);
var userP = User.find({_id:{$nin:groupP.users}});