如何使用$lookup代替populate?

编程入门 行业动态 更新时间:2024-10-10 09:24:30

<a href=https://www.elefans.com/category/jswz/34/1771452.html style=如何使用$lookup代替populate?"/>

如何使用$lookup代替populate?

我对这个很陌生,我发现我必须使用 $lookup 而不是我的代码中的populate。由于我没有这方面的经验,我需要一些帮助,如何在下面的代码中做到这一点。

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代替这个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}},
    {
        $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",
            ...
        }
    }
])

更多推荐

如何使用$lookup代替populate?

本文发布于:2024-05-13 11:16:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1759473.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   lookup   populate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!