如何使用猫鼬按引用查找嵌套值

时间:2020-07-02 14:29:47

标签: javascript node.js mongoose

我想按参考值查询。我有以下型号:

//Room Model
const RoomSchema = new Schema({
  name: { type: String, required: true },
  status: {type: String, required: true},
});

module.exports = mongoose.model('Room', RoomSchema);

和引用我的Room模型的RoomUser模型:

//RoomUserModel
const RoomUserSchema = new Schema({
    user : {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    room: {type: mongoose.Schema.Types.ObjectId, ref: 'Room'},
    status: {type: String, required: true},
});

module.exports = mongoose.model('RoomUser', RoomUserSchema);

我想要做的就是通过像这样的参考房间名称来找到结果

const roomUsers = await RoomUser.find({'room.name' : 'ROOM_NAME_001'}, function(err) {
     //TODO
}).populate('user').populate('room');

但是那之后我什么也没得到,只是一个空的[]。

您能帮助我了解我在做什么错,这是正确的做法吗?

致谢! =)

1 个答案:

答案 0 :(得分:0)

可能有两种方法。

方法1:使用汇总和查找

db.RoomUser.aggregate(
  [
    { 
        "$lookup": {
            "from": "Room",
            "localField": "room",
            "foreignField": "_id",
            "as": "rooms"
        }
    },
    { 
        "$lookup": {
            "from": "user",
            "localField": "user",
            "foreignField": "_id",
            "as": "user"
        }
    },
    { "$match": { "rooms.name": "ROOM_NAME_001" }},
  ],
  function(err, result) {
    // "rooms" is now filtered by name
  }
)

方法2:使用猫鼬填充:

RoomUser.find().populate({
      path: 'room',
    },
    {
        path: 'user'
    }).exec(function(err, roomuser) {
      roomuser = roomuser.filter(function(ru) {
        return ru.name == "ROOM_NAME_001";
      });
    });