I have this circuit:
const guestSchema = new Schema({
id: String,
cart: [
{
product: {
type: mongoose.Schema.ObjectId,
ref: "products"
},
quantity: Number
}
]
});
I have this query:
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);
});
Basically, what I'm trying to do is conditional update. I tried to use $cond, but found out that the operator is not used for queries, as I do.
Based on this:
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }
I want something similar to the functionality of this statement for my request.
Let me break my condition:
For my boolean expression: I want to check if req.body.itemID $neany of the values in my cart matches
If true, then: $pushitemID and quantity in the cart
Else (then the item already exists): $incquantity by 1
Question: How to achieve this result? Do I need to make two separate requests? I try to avoid this if possible