Node.js sails.js多对多查询
我正在尝试建立一个聊天应用程序。我有一个多对多的协会。一个房间有很多用户。一个用户可以有很多房间。我正在尝试检索包含用户A(fromUserId)和用户B(toUserId)的文件室。我正在尝试类似的方法,但我知道这是不对的:Node.js sails.js多对多查询,node.js,many-to-many,sails.js,waterline,Node.js,Many To Many,Sails.js,Waterline,我正在尝试建立一个聊天应用程序。我有一个多对多的协会。一个房间有很多用户。一个用户可以有很多房间。我正在尝试检索包含用户A(fromUserId)和用户B(toUserId)的文件室。我正在尝试类似的方法,但我知道这是不对的: Room.find().populate('users', { where:{ id: [fromUserId, toUserId] } }).exec(function(err, rooms){ console.log(rooms); }); 这里的问题是,它返回
Room.find().populate('users', { where:{ id: [fromUserId, toUserId] } }).exec(function(err, rooms){
console.log(rooms);
});
这里的问题是,它返回users.id=fromUserId或toUserId的任何房间。这里我需要的是一个和查询
谢谢你的帮助。(:即使使用原始SQL,也很难做到这一点。最好的办法是获取每个用户所在的所有房间,然后获取交叉点:
// 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
,您可以使这一点更加优雅,而且不要忘记处理错误!即使使用原始SQL,您也很难做到这一点。您最好的办法是获取每个用户所在的所有房间,然后获取交叉点:
// 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
,使其更加优雅,并且不要忘记处理您的错误!如果您将Mongodb与waterline一起使用,您可以在中使用$
Room.native(function(err, collection) {
collection.find({
"users" : {
$in : [fromUserId, toUserId]
}
}, function(err, results) {
if (err) return res.badRequest(err);
console.dir(results)
});
});
缺点是它的原生mongodb特性,您不能在其他数据库中使用。如果您将mongodb与waterline一起使用,您可以在中使用$
Room.native(function(err, collection) {
collection.find({
"users" : {
$in : [fromUserId, toUserId]
}
}, function(err, results) {
if (err) return res.badRequest(err);
console.dir(results)
});
});
缺点是它的原生mongodb功能,你不能在其他数据库中使用。你在使用哪个数据库?Ryan Wu mongodb with waterline或你在使用哪个数据库?Ryan Wu mongodb with waterline ORM我也这么做了,但我希望ORM中有一些魔力。谢谢。(:我也这么做了,但我希望ORM能有点魔力。谢谢