skip to Main Content

I’m fairly new to mongodb and I’ve been messing around with this for some time and can’t get it right. I need to use a $set with a condition to set a field only if it doesn’t exist:

$set: {
    theField: { $ifNull: ['$theField', '1234'] },
  }

this is passed in as update: UpdateQuery<T>which gives the error "CastError: Cast to string failed for value "{ '$ifNull': [ '$source7ChargeCode', '1234' ] }" (type Object) at path "source7ChargeCode"n at model.Query.exec

Does anyone have any tips?

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for the advice guys! Based on the responses I was able to see that I was using aggregation and to add these type queries to mongoose update methods you need to use UpdateWithAggregationPipeline object and then wrap it in [] to make it an array.


  2. you can use ifNull just in aggregation nor in update query.

    refer to ifNull (aggregation) link for more info.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search