how to get data from 3 collections in mongodb using node js?

前端 未结 2 518
甜味超标
甜味超标 2021-01-19 21:21

I have the below collections in mongodb

db.orders.find()

{ \"_id\" : ObjectId(\"5cc69ad493297eade15bacb7\"), \"item\" : \"card\         


        
2条回答
  •  说谎
    说谎 (楼主)
    2021-01-19 21:50

    There are 2 issues in your query:

    1. The field user_mob (orders schema) is a Number while mobile_no (user_nippon schema) is a String therefore the lookup cannot be made. You might want to use the same type for those fields.

    2. The second lookup is incorrect. the first lookup and unwind returns your item element inside the orders_data element so the localField of this lookup should be changed to: orders_data.item

    So after you change both user_mob and mobile_no to have matching types your query would look like this:

    db.collection('users_nippon').aggregate([
                {
                    $lookup: {
                       from: "orders",
                       localField: "mobile_no",
                       foreignField: "user_mob",
                       as: "orders_data"
                    }
                },
                {
                    $unwind: "$orders_data"
                },
                {
                    $lookup: {
                        from: "items",
                        localField: "orders_data.item",
                        foreignField: "item",
                        as: "items_data"
                    }
                },
                {
                    $unwind: "$items_data"
                }
            ]).toArray(function(err, list) {
                if (err) throw err;
                console.log(JSON.stringify(list));
                res.send(JSON.stringify(list));
                });
    
    

提交回复
热议问题