Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
Conditional push or replace of subdocument in array

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!