javascript - 在nodejs中将数字作为intiger插入mongodb
问题描述
错误
UnhandledPromiseRejectionWarning : MongoError: $multiply only supports numeric types, not string
问题是我已经拿走了购物车中产品的总和。但价格是字符串格式...解析 Int 不起作用有没有办法将数字作为数字插入数据库
添加产品代码
addProduct: (product, callback) => {
db.get().collection('product').insertOne(product).then((data) => {
callback(data.ops[0]._id)
})
}
**求和并返回**
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:['$quantity','$product.price']}}
}
}
]).toArray()
console.log(total[0].total);
resolve(total)
})
解决方案
推荐阅读
- flutter - 使用 MapBox 插件在 Flutter 中添加自定义标记
- php - [Route: rekap.laba] [URI: rekapan/laba1/{tanggal}] [缺少参数:tanggal] 缺少必需参数
- google-cloud-dataflow - 使用 Google Dataflow 模板,是否有简单的方法将数据库中的所有表列入白名单,而不是传递所有表的逗号分隔列表
- angular - Angular:动态添加的js在路由后不起作用
- php - Debian - Apache MySQL PDO 问题,但所有日志都是空的
- amazon-web-services - RedShift - update table with date from a timestamp column
- java - 如何将 Web 元素的名称存储转换为字符串?
- python - ImportError:无法从“contacts.api.serializers”导入名称“CustomerIdNameSerializer”
- python-3.x - matplotlib 在我的 x 轴上自动生成日期
- regex - 在 linux shell 中使用正则表达式从文本文件中提取字符串、grep IP 地址但使用 CIDR 排除子网