0

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?

ForestG
  • 17,538
  • 14
  • 52
  • 86

1 Answers1

0

Woops, found the answer here.

Basically, I cannot insert and increment the same field in the same query.

So I should do this:

return DailyStatisticsCollecion.findOneAndUpdate({
            date: helpers.getTodayDate()
        },
        {
            $setOnInsert: {
                date: helpers.getTodayDate(),
            },
            $inc: {
                totalVisits: 1,
                ['hourStats.' + currentHour + '.newUsers']: 1
            },
        },
        {
            upsert: true, 
            setDefaultsOnInsert: true 
        },
    )

This way the object did not get created though. So if anybody knows a full solution, with which I can create the "emtpy" object AND increment a value if needed, it would be much appreciated.

ForestG
  • 17,538
  • 14
  • 52
  • 86