I am facing a challenge with executing an updateOne() query on my database. The objective is to increment a specific value in a document if an object within an array in the document has an _id that matches a certain value. If there are no matches with that _id, I need to push a new object to the array.
Here is the simplified schema:
const userSchema = new Schema({
_id: String
counting: [{
_id: String,
score: Number
}]
})
const UserModel = mongoose.model('User', userSchema)
Below is the attempted query which is not functioning as expected, along with example _id values:
const userId: '5'
const countingId: '2'
await UserModel.updateOne(
{ _id: userId},
{ counting: {
$cond: {
if: { $in: [ countingId, '_id' ] },
then: { $inc: { 'score': 1 } },
else: { $push: { _id: countingId, score: 1 } }
}
} }
)
Assuming the current database contains a document like this:
{
_id: 5,
counting: {
_id: 2,
score: 50
}
}
After executing the query, the document ends up like this:
{
_id: 5,
counting: {
score: 0
}
}
When the query finds a match with the countingId, it mistakenly removes the 'counting._id' field and resets the score to 0. If no matches are found, nothing changes. I seek assistance in understanding why this query fails and how I can rectify it.