繁体   English   中英

如何使用 $lookup 而不是填充

[英]How to use $lookup instead of populate

我对此很陌生,我发现我必须使用$lookup而不是在我的代码中填充。 由于我没有这方面的经验,因此我需要一些帮助来了解如何对下面的代码进行操作。

postSchemaModel.aggregate([{
        "$geoNear": {
            "near": { "type": "Point", "coordinates": [6.7336665, 79.8994071], "Typology": "post" },
            "distanceField": "dist.calculated",
            "maxDistance": 5000,
            "includeLocs": "dist.location",
            "spherical": true
        }
    },
    { "limit": limit },
    { "skip": startIndex },
    { "$sort": { "createdAt": -1 } },
    { "populate": user_id },
    { "populate": "'user_id', 'img user_name _id'" }

]).then(async function(posts) {
    //some code here
});

我想使用 $lookup 而不是这个填充 function。 请帮忙

下面是如何使用基本$lookup语法的速写。 我不得不推测一些字段名称,因为您没有包含所有 collections 的架构,但如果它们是错误的,它应该是相当直接的修复。

postSchemaModel.aggregate([
    {
        "$geoNear": {
            "near": {"type": "Point", "coordinates": [6.7336665, 79.8994071], "Typology": "post"},
            "distanceField": "dist.calculated",
            "maxDistance": 5000,
            "includeLocs": "dist.location",
            "spherical": true
        }
    },
    {"limit": limit},
    {"skip": startIndex},
    {"$sort": {"createdAt": -1}},
    {
        $lookup: {
            from: "users", //user collection name,
            localField: "user", // this is the field in the post document that links to user
            foreignField: "_id", // this is the field in the user document that links to localField specified above.
            as: "users" // name of new field
        }
    },
    // users is now an array of matched users (could be an empty array if no user was matched), assuming a post can only have 1 user we should unwind this
    {
        $unwind: {
                path:"$users"
                preserveNullAndEmptyArrays: true // true if you want to keep posts with no matched user.
         }
    },
    {
        //now you can $project whichever structure you want
        $project: {
            user_id: "$users._id",
            ...
        }
    }
])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM