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

280
Views
Conditional operator in mongoose

I am trying to conditionally execute two different mongoose operators but it just return no error and doesn't work to update the document.

My Schema:

const CartSchema: Schema<Document<ICart>> = new Schema({
    clientID: { type: String, required: true },
    sourceID: { type: String, required: true },
    items: { type: Array },
    source: { type: String, required: true },
}, { collection: "carts", timestamps: true });

The way I am trying to implement that:

await CartModel.findOneAndUpdate(
    { sourceID: clientID, 'items.id': Types.ObjectId(itemID) }, 
    { 
         $cond: { 
              if: {
                  $eq: 1,
              },
              then: { $pull: { 'items.$.id': Types.ObjectId(itemID) }},
              else: { $inc: { 'items.$.amount': -1 }},
         }
    }, 
    { new: true }
).lean({ virtuals: true })

And I also tried to have this kind of query: { sourceID: clientID } but it didn't help. I thought maybe I could not find the element and it just silently pass through.

The main idea here of what I am gonna do is - have a conditional mongoose request where I'll either remove the object from the array if the current value in the field amount is equal to 1, or decrement the value to -1.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Apparently, the $cond operator works only in the aggregation framework but in my Atlas tier I cannot check if the query works properly, but I suppose it should look something like this:

           await CartModel.aggregate([
                { $match: {
                    sourceID: clientID, 
                    'items.id': Types.ObjectId(itemID)
                    }
                }, 
                { 
                    $cond: { 
                        if: {
                            $eq: 1,
                        },
                        then: { $pull: { 'items.$.id': Types.ObjectId(itemID) }},
                        else: { $inc: { 'items.$.amount': -1 }},
                    }
                }
            ])
over 4 years ago · Santiago Trujillo Report
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!