我有这个架构:
const guestSchema = new Schema({
id: String,
cart: [
{
product: {
type: mongoose.Schema.ObjectId,
ref: "products"
},
quantity: Number
}
]
});
我有这个问题:
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);
});
基本上,我要做的是根据条件进行更新。我尝试使用 $cond
,但发现该运算符并不像我正在做的那样用于查询。
基于此:
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }
我的查询需要类似于此运算符功能的东西。
让我们分解一下我的情况:
对于我的 bool 表达式:我想检查 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();
}
});
关于mongodb - Mongoose 查询使用 if else possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49449179/