sails.js多对多查询

我正在尝试构build一个聊天应用程序。 我有一个多对多的关联。 一个房间有很多用户。 而且用户可以有很多房间。 我试图检索既有用户A(fromUserId)和用户B(toUserId)的房间。 我正在尝试这样的事情,但我知道这是不正确的:

Room.find().populate('users', { where:{ id: [fromUserId, toUserId] } }).exec(function(err, rooms){ console.log(rooms); }); 

这里的问题是,它返回任何房间users.id = fromUserId toUserId。 我需要的是一个查询。

任何帮助赞赏。 (:

如果你使用Mongodb和waterline,你可以使用$ in

 Room.native(function(err, collection) { collection.find({ "users" : { $in : [fromUserId, toUserId] } }, function(err, results) { if (err) return res.badRequest(err); console.dir(results) }); }); 

缺点是它的本地mongodbfunction,你不能在其他数据库中使用。

即使使用原始SQL,也很难做到这一点。 你最好的select是获得每个用户所在的所有房间,然后得到十字路口:

 // Get the fromUser and their rooms User.findOne(fromUserId).populate('rooms').exec(function(err, fromUser) { // Get the toUser and their rooms User.findOne(toUserId).populate('rooms').exec(function(err, toUser) { // Get the IDs of the rooms they are both in var fromUserRoomIds = _.pluck(fromUser.rooms, 'id'); var toUserRoomIds = _.pluck(toUser.rooms, 'id'); var sharedRoomIds = _.intersection(fromUserRoomIds, toUserRoomIds); // Find those rooms Room.find({id: sharedRoomIds}).exec(...); }); }); 

你可以使用async.auto使这更优雅,不要忘记处理你的错误!