node.js - Can not convert a string to number, (price of a product) which is taken from mongodb collection by query
问题描述
Hai I am new in nodejs and mongodb.I have to find the total price of a shopping cart.But when multiplying product quantity with price ,the price can not convert to number.when using parseInt result shows Nan. Here is my code:
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: {
_id: 1, item: 1, quantity: 1, product: { $arrayElemAt: ['$product', 0] }
}
},
{
$group:
{
_id:null,
total:{$sum:{$multiply:['$quantity',parseInt('$product.price')]}}
}
}
]).toArray()
console.log(total)
resolve(total)
}
)
}
result showing:
[ { _id: null, total: NaN } ]
解决方案
您可以使用 $convert 运算符将字符串转换为数字
推荐阅读
- react-native - 视图中的中心元素 - React-Native
- rdf - 清除 GraphDB 免费中的命名图很慢
- sql-server - 如何从 SQL Server 记录集查询和其他约束中获取第一行
- node.js - UnhandledPromiseRejectionWarning: CastError: Cast to string failed for value in mongoose
- php - 在 PHP 中使用 DateTime 解析毫秒时间戳
- html - Legacy Selenium IDE - 如何手动制作合适的 xpath
- typescript - 快速删除工作但未找到错误
- python - numpy bitwise_and 无法将参数 1 广播到输出数组
- pine-script - Tradingview JS API 从其用户自定义指标中获取处理后的数据
- javascript - 如何使用 JavaScript 中的用户输入调用包含 If/Else 的函数