如何在使用nodejs的对象ID引用中在mongo中查找?

时间:2019-02-20 03:25:43

标签: node.js mongodb express mongoose

我有两个模式

var UserSchema  =new mongoose.Schema({
    username:String,
    password:String,
    user_email:String,
    user_contacts:[
        {
            type:mongoose.Schema.Types.ObjectId,
            ref:"User"
        }
    ]
})
module.exports=mongoose.model("User",UserSchema);

var friendRequestSchema=new mongoose.Schema({
    requester:{
        type:mongoose.Schema.Types.ObjectId,
        ref:"User"
    },
    recipient:{
        type:mongoose.Schema.Types.ObjectId,
        ref:"User"
    },
    //1 for requested , 2 for accepted , 3 for rejected
    status:Number
});
module.exports=mongoose.model("FriendRequest",friendRequestSchema);

并且我想为 requester 字段查找所有具有特定用户ID的朋友请求,然后我希望获得这些请求的所有收件人用户, 最后将它们添加到词典中,其中的键是收件人用户,值是与之关联的 friendRequest ,这样我就可以将其传递给这样的ejs文件: / p>

res.render("myrequests",{myDictionary:myDictionary});

1 个答案:

答案 0 :(得分:2)

您现在可以使用$lookup

在Mongo 3.2中做到这一点

$ lookup需要四个参数

from:在同一数据库中指定要执行连接的集合。无法对from集合进行分片。

localField:指定从文档输入到$ lookup阶段的字段。 $ lookup对from集合中的文档中的localField和foreignField执行相等的匹配。

foreignField:指定from集合中文档中的字段。

as:指定要添加到输入文档中的新数组字段的名称。新的数组字段包含from集合中的匹配文档。

db.Foo.aggregate(
  {$unwind: "$bars"},
  {$lookup: {
    from:"bar",
    localField: "bars",
    foreignField: "_id",
    as: "bar"

   }},
   {$match: {
    "bar.testprop": true
   }}
)

希望这可以解决您的问题!

相关问题