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?