I've got a user schema,
const userSchema = new mongoose.Schema({
name:{
type: String,
required: [true, "Provide Username"],
unique: true
},
password: String,
orders:[{seriesName: String, order:[Schema.ObjectId], _id: false}]
});
I want to update or upsert the subdocument in orders: If there is not already a subdocument with the seriesName (e.g. "Flash") then, I would push the new document. If there is a subdocument with the seriesName, then I would change the order array in the subdocument.
app.patch("/users/:series", (req, res)=>{
let userName = req.body.name;
let seriesName = req.params.series;
let orderString = req.body.order;
order = JSON.parse(orderString);
let orderIDValues = [];
order.forEach(orderIDString=>{
orderIDValues.push(mongoose.Types.ObjectId(orderIDString))
});
User.updateOne(
{name: userName},
{$cond:{
if: {$in: [seriesName, "$orders.seriesName"]},
then: {"$orders.seriesName": {$in: [seriesName]},
$set:{order: order}},
else: {$push:{
orders: {seriesName: seriesName, order: order}
}}}}, (err, result)=>{
if(!err){
res.send(result);
} else{
res.send(err);
}
}
)
});
All that gets returned is {"acknowledged":false}
I've worked out the code to simply push a new subdocument or replace the order in the appropriate subdocument. I'm suspecting, I'm not understanding the $cond aggregation.