Search code examples
node.jsvisual-studio-codevisual-web-developer

$in requires an array as a second argument, found: missing, this error showing


i am doing e-commerce website and user come and take products to cart.i want to show the products in cart but showing error

                getCartProducts: (userId) => {
    return new Promise(async (resolve, reject) => {
        let cartItems = await db.get().collection(collection.CART_COLLECTION).aggregate([
            {
                $match: { user: new ObjectId(userId) }
            },
            {
                $lookup: {
                    from: collection.PRODUCT_COLLECTION,
                    let: { prodList: '$products' },
                    pipeline: [
                        {
                            $match: {
                                $expr:{
                                    $in: ['$_id', "$$prodList"] 
                                }
                            }
                        
                        }
                    ],
                    as: 'cartItems'
                }
            },
            {
                $project: {
                    cartItems: 1
                }
            }
        ]).toArray();
        resolve(cartItems);
    });
}

this is my code with $in .but showing error please anyone can help me


Solution

  • Please ensure $$prodList is an array as $in accepts only Array values.

    Here below is the code to have some extra check to ensure $$prodList is an array

    pipeline: [
        {
            $match: {
    
                $expr: { $eq: [{ $type: "$$prodList" }, "array"] }
            }
        },
        {
            $match: {
                $expr: {
                    $in: ['$_id', "$$prodList"]
                }
            }
        }
    ],
    

    Adding another $match in your pipeline will ensure you have $$prodList as an array.