【发布时间】:2020-09-04 04:29:43
【问题描述】:
let cart = req.body.params.cart // array of objects that needs to be updated if exists in db, if not upsert it.
let userid = req.body.params.uid
for (let i = 0; i < cart.length; i++) {
Cart.updateOne({ user: userid, 'cart.product': cart[i].product._id },
{
$set: {
'cart.$.quantity': cart[i].quantity
}
},
{ upsert: true }// works without this line of code, updates the objects if exists
)
}
我的购物车型号:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CartSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
cart: [{
product: {
type: Schema.Types.ObjectId,
ref: 'productlist'
},
quantity: {
type: Number
},
date: {
type: Date,
default: Date.now
}
}]
})
module.exports = Cart = mongoose.model('cart', CartSchema)
我正在尝试使用购物车数组中的新商品更新用户购物车。我需要检查产品是否存在,如果是更新数量,如果不将其推入用户的购物车。不知何故,它不适用于 $upsert。如果对象 id 存在于用户的购物车中,则没有 $upsert 的文档会得到更新。
具有大量混乱的工作版本。我觉得有一种更好的方法可以做到这一点,就像我在上面尝试做的那样。我会感谢任何帮助,减少这里的混乱。
Cart.find({ user: req.body.params.uid })
.then(userCart => {
if (userCart[0].cart.length === 0) {
for (let i = 0; i < cart.length; i++) {
Cart.updateOne({ user: req.body.params.uid }, {
$push: {
cart: {
product: cart[i].product._id,
quantity: cart[i].quantity
}
}
}).catch(err => console.log(err))
}
}
else {
cart.reduce((acc, element) => {
let index = userCart[0].cart.findIndex(val => val.product._id == element.product._id)
if (index !== -1) {
Cart.findOneAndUpdate({ user: req.body.params.uid, 'cart.product': element.product._id },
{
$set: {
'cart.$.quantity': element.quantity
}
},
{ new: true }
).then(a => console.log(a))
}
else {
Cart.updateOne({ user: req.body.params.uid }, {
$push: {
cart: {
product: element.product._id,
quantity: element.quantity
}
}
}).catch(err => console.log(err))
}
acc.push(element)
return acc
}, [])
}
})
来自数组购物车的样本值
product: {
_id: '5eaf8eeac436dbc9b7d75f35',
name: 'Strawberry',
category: 'organic',
image: '/productImages/australian.jpg',
price: '9.65'
},
quantity: 6
数据库中的样品车:
_id: 5ec12ea36ccf646ff5aeef0c,
user: 5ec11a8f69ccf46e0e19c5ef,
cart: [
{
date: 2020-05-18T10:26:38.751Z,
_id: 5ec262de5829f081b1ea96d7,
product: 5eaf8eeac436dbc9b7d75f35,
quantity: 8
},
{
date: 2020-05-18T12:11:57.168Z,
_id: 5ec27b8dd2949886308bebd6,
product: 5eaf8f61c436dbc9b7d75f36,
quantity: 6
}
]
【问题讨论】:
-
这能回答你的问题吗? MongoDB: upsert sub-document
-
不是真的,谢谢你的参考。 @PuneetSingh
-
@PuneetSingh 发布并更新仅供参考..
-
您能否也发布您在 cart.reduce 中使用的数组购物车的示例值
-
收到的购物车是满的购物车吗?或者如果我有一个与其他产品一起保存的“旧”购物车,我们应该维护它们?
标签: javascript node.js mongodb mongoose