0

I have model: where stats.d is current date and t and u are some statistics.

name: string,
stats: [{
  d: {type: date, default: moment().format('MM/DD/YYYY')},
  t: number,
  u: number,
}],
total: number

what I am trying to do is to update, check if date is today if today increment t, if today date is not exist, create or add entry to stats array with current date and starting t point. So that I will have stats by date. Here is what I have tried.

 model.findOneAndUpdate({_id:req.params._id}, {$set:{"stats.d": date}, $inc: {total: 1, "stats.t": 1}}, {upsert:true}, function(err, data){

 //success
});

But it is not working. I get following error:

can't append to array using string field name: t","code":13048,"ok":0

Could any point out the issue?

1 Answer 1

1

I don't think you can do this in one update query.

But you can use javascript:

model.findOne(
    {
        _id: ObjectId("req.params._id")
    },
    function(err, data){
        var isDateFound = false;

        for (var i = 0; i < data.stats.length; i++) {
            if (data.stats[i].d === date) {
                isDateFound = true;
                data.stats[i].t++;
                break;
            }
        }

        if (!isDateFound) {
            data.stats.push({
                d: date,
                t: 1,
                u: 0
            })
        }

        data.total++;

        model.save(data) // or data.save() should work as well
});

Without the upsert requirement, it's possible to increment the matched array element:

db.test.update(
    {
        _id: ObjectId("req.params._id"),
        'stats.d': date
    },
    {
        $inc: {
            'stats.$.t': 1,
            'total': 1
        }
    }
)
Sign up to request clarification or add additional context in comments.

3 Comments

Not all, but I need to update stats.t where stats.d is current date as well as total
@karma so change your question accordingly, it's not understood at all. it looks like you are trying to update all elements.
Yes you are right, that's what I did, with javascript. Slightly different code, but same concept.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.