Home > Net >  MongoServerError: PlanExecutor error during aggregation how to fix?
MongoServerError: PlanExecutor error during aggregation how to fix?

Time:09-27

in the shopping cart project, am trying to get the total amount in the cart but my aggregation method has some problems , how to fix this ?

error

callback(new error_1.MongoServerError(document));
                             ^
MongoServerError: PlanExecutor error during aggregation :: caused by :: Failed to parse number '1,39,999' in $convert with no one rror value: Did not consume whole string.

user_helpers.js this the aggregation

getTotalAmount:(userId)=>{
    return new Promise(async(resolve,reject)=>{
        let total=await db.get().collection(collection.CART_COLLECTION).aggregate([
            {
                $match:{user:objectId(userId)}
            },
            {
                $unwind:'$products'
            },{
                $project:{
                    item:'$products.item',
                    quantity:'$products.quantity',
                 
                }
            },
            {
                $lookup:{
                    from:collection.PRODUCT_COLLECTION,
                    localField:'item',
                    foreignField:'_id',
                    as:'product'
                }
            },
            {
                $project:{
                    item:1,quantity:1,product:{$arrayElemAt:['$product',0]}
                } 
            },
            {
                $group:{ 
                    _id:null, 
                    total:{$sum:{$multiply:[{ $toInt: '$quantity'},{ $toInt: '$product.Price' }]}}  // my assumption , here comes the error
                } 
            }
 
        ]).toArray()
       
        resolve(total.length > 0 ? total[0].total: 0)  // or here
    })
} 

user.js

// GET: view shopping cart contents

router.get('/cart',middleware.verifyLogin,async(req,res,next)=>{
   try{
      let user=req.session.user._id;
      let products =await userHelpers.getCartProducts(req.session.user._id)
      let totalValue=0 
      if(products.length>0){   
      totalValue=await userHelpers.getTotalAmount(req.session.user._id)
      let proId=req.params.id
      console.log('proId>>>>>>>>>>',proId);
      }
     
    console.log('products>',products)
      console.log("user...",user);
    res.render('user/cart',{products,user,totalValue,});

}catch (error) {
   console.log(error);
 }
 
})

It comes when you click the cart button error is getting , how to fix this ?

CodePudding user response:

The error message says itself, your database contains strings like 1,39,999. When MongoDB tries to convert these to an integer, it fails because of the commas. So, before converting the string to an integer, you should remove all the commas and other non-numeric characters from the string. Like this:

db.collection.aggregate([
  {
    $match: {
      user: ObjectId("userId433456666666666666")
    }
  },
  {
    $unwind: "$products"
  },
  {
    $project: {
      item: "$products.item",
      quantity: "$products.quantity",
      
    }
  },
  {
    $lookup: {
      from: "collection.PRODUCT_COLLECTION",
      localField: "item",
      foreignField: "_id",
      as: "product"
    }
  },
  {
    $project: {
      item: 1,
      quantity: 1,
      product: {
        $arrayElemAt: [
          "$product",
          0
        ]
      }
    }
  },
  {
            $group: {
              _id: null,
              total: {
                $sum: {
                  $multiply: [
                    {
                         $toInt: '$quantity'
                    },
                    {
                      $toInt: {
                        "$replaceAll": {
                          "input": "$product.Price",
                          "find": ",",
                          "replacement": ""
                        }
                      }
                    }
                  ]
                }
              }
            }
          }
    ]).toArray()

Here we are using $replaceAll to replace the commas with an empty string.

  • Related