MongoServerError:PlanExecutor聚合过程中的错误如何修复



在购物车项目中,我试图获得购物车中的总额,但我的聚合方法有一些问题,如何解决?

错误

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

user_helpers.js这是聚合

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:查看购物车内容

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);
}

})

当你点击购物车按钮时,错误就会出现,如何解决这个问题?

错误消息本身表明,您的数据库包含类似1,39,999的字符串。当MongoDB试图将这些转换为整数时,由于逗号的原因,它失败了。因此,在将字符串转换为整数之前,应该从字符串中删除所有逗号和其他非数字字符。像这样:

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()

这里我们使用$replaceAll将逗号替换为空字符串。

相关内容

  • 没有找到相关文章

最新更新