skip to Main Content

Product Collection:

[
        {
            "isActive": true,
            "_id": "643bbdee68b521035e20c976",
            "name": "lu",
            "price": 123,
            "userId": "643abd0dcce4df3b1a0c8fa7"
        },
         {
            "_id": "643bbdd668b521035e20c972",
            "name": "mu",
            "price": 123,
            "userId": "643abd0dcce4df3b1a0c8fa7",
            "isActive": true,
            "__v": 0
        },
         {
            "isActive": true,
            "_id": "643bbdbc68b521035e20c971",
            "name": "nu",
            "price": 123,
            "userId": "643abd0dcce4df3b1a0c8fa7"
        },
         {
            "_id": "643c2dc126211992b4ee8fd5",
            "name": "pu",
            "price": 123,
            "userId": "643abd0dcce4df3b1a0c8fa7",
            "isActive": true
        }
    ]

Subproduct Collection:

[
        {
            "_id": "643d7ed82cd5b5fcd7e81e02",
            "name": "kkkk",
            "phoneNum": 9543922499,
            "productID": "643bbdee68b521035e20c976",
            "user": "643abd0dcce4df3b1a0c8fa7",
            "address": {
                "address1": "243, bastin nagarsss",
                "zipCode": 6250185
            }
        }
    ]

My aggregare function:

aggregateLookup: async () => {
    try {
        let subProduct = await SubProduct.aggregate([
            {
                $lookup: {
                    from: "Product",
                    localField: "productID",
                    foreignField: "_id",
                    as: "product_Details"
                }
            }
        ]);

        return subProduct;
    } catch (error) {
        throw new Error(error);
    }
}

MY SCHEMA:

const subProduct = new mongoose.Schema({
  name: {
    type: String,
    required: [true,'Name is Required...']
  },
  phoneNum: {
    type: Number,
    required: true,
    validate: {
      validator: (value) => {
        return `${value}`.length === 10;
      },
      message: 'Should be 10 digit Number'
    }
  },
  productID: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: 'Product'
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: 'User'
  },
  address: {
    address1: String,
    zipCode: Number
  }
});

In Schema I’m having Product id type as ObjectID. In aggregateLookup function I need to retrieve all data using $lookup I’m having the related product in Product Document But its still returning an empty array.

My output is coming with Product_Details as empty but having data in Product Documents:

[
    {
        "_id": "643d7ed82cd5b5fcd7e81e02",
        "name": "kkkk",
        "phoneNum": 9543922499,
        "productID": "643bbdee68b521035e20c976",
        "user": "643abd0dcce4df3b1a0c8fa7",
        "address": {
            "address1": "243, bastin nagarsss",
            "zipCode": 6250185
        },
        "product_Details": []
    }
]

Expected Output:

[
    {
        "_id": "643d7ed82cd5b5fcd7e81e02",
        "name": "kkkk",
        "phoneNum": 9543922499,
        "productID": "643bbdee68b521035e20c976",
        "user": "643abd0dcce4df3b1a0c8fa7",
        "address": {
            "address1": "243, bastin nagarsss",
            "zipCode": 6250185
        },
        "product_Details": [
        {
        "isActive": true,
        "_id": "643bbdee68b521035e20c976",
        "name": "lu",
        "price": 123,
        "userId": "643abd0dcce4df3b1a0c8fa7"
        }
        ]
    }
]

Please help me What mistake I have made I’m new to mongodb. Thanks in advance…

2

Answers


  1. Chosen as BEST ANSWER

    @Rituparan i checked some document i prepared the below query its not working as expected its comming dirrect child of SubProject with empty array.

    await SubProduct.aggregate([
                    {
                        $lookup: {
                            from: "products",
                            localField: "productID",
                            foreignField: "_id",
                            as: "product_Details"
                        }
                    },
                    {
                        $unwind: "$product_Details"
                    },
                    {
                        $lookup: {
                            from: "users",
                            localField: "product_Details.userId",
                            foreignField: "_id",
                            as: "user_Details"
                        }
                    },{
                        $project: {
                            "user_Details.password": 0
                        }
                    }
                ]);
    

    But my output is

    [
        {
            "_id": "643d7ed82cd5b5fcd7e81e02",
            "name": "kkkk",
            "phoneNum": 9543922499,
            "productID": "643bbdee68b521035e20c976",
            "user": "643abd0dcce4df3b1a0c8fa7",
            "address": {
                "address1": "243, bastin nagarsss",
                "zipCode": 6250185
            },
            "product_Details": {
                "_id": "643bbdee68b521035e20c976",
                "name": "lu",
                "price": "123",
                "userId": "643abd0dcce4df3b1a0c8fa7"
            },
            "user_Details": []
        }
    ]
    

    I like to have user_Details with values under Product_Details so in query $lookup from "user" i added localField as "Product_Details.userId" still not working. What mistake i done. Plz let me know. I using MongoDB version 5.0.

    Expected Output:

    [
      {
        "_id": "643d7ed82cd5b5fcd7e81e02",
        "address": {
          "address1": "243, bastin nagarsss",
          "zipCode": 6.250185e+06
        },
        "name": "kkkk",
        "phoneNum": 9.543922499e+09,
        "productID": "643bbdee68b521035e20c976",
        "product_Details": [
          {
            "_id": "643bbdee68b521035e20c976",
            "isActive": true,
            "name": "lu",
            "price": 123,
            "userId": "643abd0dcce4df3b1a0c8fa7",
            "user_Details": [
              {
                "_id": "643abd0dcce4df3b1a0c8fa7",
                "age": 23,
                "name": "Rituparna Warwatkar"
              }
            ]
          }
        ],
        "user": "643abd0dcce4df3b1a0c8fa7"
      }
    ]
    

  2. The problem is surely with the names of collections.

    You have used from:"Product" instead you need to use the word products because you need to provide the exact name of the collection that is formed in the database. because mongoDB automatically assigns plural words to collection names. You can check the collection name by going to mongosh shell and

    1. To show list of all database show dbs
    2. To use a database name use db_name
    3. To list collections show collections

    https://mongoplayground.net/p/_bp4jpzUHVg

    I have tested it here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search