假设我有User
和Group
模型,群组有用户,比如
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()});
})
答案 0 :(得分:1)
您可以尝试以下查询。
var groupP = Group.findById(group_id);
var userP = User.find({_id:{$nin:groupP.users}});