Phi*_*lip 5 mongoose mongodb mongodb-query
我有这个架构:
const guestSchema = new Schema({
id: String,
cart: [
{
product: {
type: mongoose.Schema.ObjectId,
ref: "products"
},
quantity: Number
}
]
});
Run Code Online (Sandbox Code Playgroud)
我有这个查询:
Guest.findOneAndUpdate(
{ id: req.sessionID },
{
$cond: [
{ "cart.product": { $ne: req.body.itemID } },
{ $push: { "cart": { product: req.body.itemID, quantity: 1 } } },
{ $inc: { "cart.quantity": 1 } }
]
},
{ upsert: true, new: true }
).exec(function(err, docs) {
err ? console.log(err) : res.send(docs);
});
Run Code Online (Sandbox Code Playgroud)
基本上,我想做的是根据条件进行更新。我尝试使用$cond,但发现该运算符没有像我正在使用的那样用于查询。
基于此:
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }
Run Code Online (Sandbox Code Playgroud)
我想要与该运算符的功能相似的查询。
让我们分解一下我的状况:
对于我的布尔表达式:我想检查购物车中的任何值是否req.body.itemID为$ne
如果为true,则:$push放入购物车中的itemID和数量
否则(该项目已存在):$inc数量加1
问题:如何获得此结果?我需要进行两个单独的查询吗?我正在尝试避免这样做(如果可能)
我浏览了他们所有的Update Field Operators,可能没有办法按照我想要的方式做到这一点。
我想知道为什么没有$cond更新操作符。尽管如此,我已经找到了我想要实现的功能的解决方案。只是不是我想要的优雅时尚。
Guest.findOneAndUpdate(
{ id: req.sessionID },
{ id: req.sessionID }, //This is here in case need to upsert new guest
{ upsert: true, new: true }
).exec(function(err, docs) {
if (err) {
console.log(err);
} else {
//Find the index of the item in my cart
//Returns (-1) if not found
const item = doc.cart.findIndex(
item => item.product == req.body.itemID
);
if (item !== -1) {
//Item found, so increment quantity by 1
doc.cart[item].quantity += 1;
} else {
//Item not found, so push into cart array
doc.cart.push({ product: req.body.itemID, quantity: 1 });
}
doc.save();
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
794 次 |
| 最近记录: |