I want to increment a value both on document root as well as inside a nested array.
The schema
const UserPoints = new Schema(
{
points: {
type: Number,
},
monthly: {
type: [
new Schema(
{
year: {
type: Number,
},
month: {
type: Number,
},
points: {
type: Number,
min: 0,
},
},
{
_id: false,
timestamps: false,
}
),
],
},
},
{
timestamps: false,
}
);
What I have tried
Variables used: (currentYear = 2021, currentMonth = 7, addPoints = 5)
Note: The year, month may not exist in the document yet, so I need to make it work with "upsert".
UserPoints.findOneAndUpdate(
{
_id: userId,
"monthly.year": currentYear,
"monthly.month": currentMonth,
},
{
$inc: {
points: addPoints,
"monthly.$.points": addPoints,
},
},
{
upsert: true,
new: true,
}
).exec()
This does not work. And gives out an error:
{
ok:0
code:2
codeName:"BadValue"
name:"MongoError"
}
I would appreciate if someone can point me at the right direction to increment these values in the same operation.
Update: The only way that I could make it work is by first making a query to check if the (year, month) exists in the "monthly" array. Depending if it exists, I either $push the new month, or $inc the existing one's values.
addPointsvariable aNumber? - J.F.