Trying to update a dynamic field in a mongoose findAndUpdate, but with no luck.
I have the following schema:
const schema = new Schema({
date: { type: String },
totalVisits: { type: Number, default: 0},
hourStats: Object
});
hourStat is a dynamic object, created by this function:
createHourStatsObject: function () {
const hourObject = {};
for (let i = 0; i < 24; i++) {
hourObject[i] = {
newUsers: 1
}
}
return hourObject;
}
I am trying to write an insertOrUpdate
expression, with no luck. ( MongoError: Updating the path 'hourStats' would create a conflict at 'hourStats'
)
const currentHour = currentTime.getHours();
return DailyStatisticsCollecion.findOneAndUpdate({
date: helpers.getTodayDate()
},
{
$setOnInsert: {
date: helpers.getTodayDate(),
hourStats: helpers.createHourStatsObject(),
},
$inc: {
totalVisits: 1,
['hourStats.' + currentHour + '.newUsers']: 1
},
},
{
upsert: true,
setDefaultsOnInsert: true
},
)
How can I increment the hourStat
's current hour's totalVisits
value otherwise?