The dollar ($) prefixed field '$set' in '0.$set' is not valid for storage

I’m working with MongoDB 3.4.3 Community, but we will update to V4.4 soon.
also using "mongoose": "^5.8.7"
I’m Trying to UPDATE if record exists or CREATE if it doesn’t.

const myData = await this.findOneAndUpdate({
    myId,
    color,
  }, {
    $setOnInsert: {
      myId,
      color,
      date: now.format('YYYY-MM-DD'),
      counter: myObj.counter - amount,
  },
  {
    $inc: { counter: -amount }
  },
}, {
  new: true,
  upsert: true,
}).exec();

It is working fine with MongoDB v3.4 but does’t work with newer versions like 4.4 or 5.0.
using counter on both $setOnInsert and $inc causes a conflict, because both tries to set counter when at same time.

Then I tried to change the query to this:

const myData = await this.findOneAndUpdate({
    myId,
    color,
  },  [{
    $set: {
      myId,
      color,
      date: now.format('YYYY-MM-DD'),
      counter:  {
        $cond: {
          if: { $eq: ['$$ROOT', null] },
          then: myObj.counter - amount,
          else: { $subtract: ['$$ROOT.counter', amount] },
        }
      }
    }
  }], {
    new: true,
    upsert: true,
  });

Wich doesn’t work with v3.4. Not sure why, I believe I can only use this query on version 4.2 and above.

Is there a solution where could work both on Version 3.4 and 4.4?

Hi @Backenderson and welcome to the MongoDB community forum!!

To understand the requirement in a more better way, could you help me with a sample document and the desired output for the same which would help me to replicate in my local environment and help you with the solution.

If you’re considering upgrading, I would recommend updating to the latest version of as it will offer far more features and flexibility for you to work more efficiently.

Please refer to the documentation on How to upgrade to latest version of MongoDB documentation for smooth upgrade.

Let us know if you have any more concerns.

Best Regards
Aasawari