Search code examples
node.jsmongodbexpressmongoosemongoose-populate

Increment nested mongoose shcema


This is my model:

const telemetery = mongoose.Schema({
link: String,
originalLink: String,
creator: {
    type: mongoose.Schema.Types.ObjectId
},
browerType: {
    Firefox: Number,
    Chrome: Number,
    Edge: Number,
    IE: Number,
    Safari: Number,
    Other: Number
}

I want to increment the value of the firefox by 1

What I am doing now:

const test = await Telemetery.findOneAndUpdate({link: req.params.link}, {browserType: {$inc : {Firefox : 1}}})

But this still id not updating the document. At the end I would also like to use a variable instead of Firefox so that the value is incremented dynamically with depending on the input.

Can anyone please help?


Solution

  • To increment the value in a nested object you can use the dot notation

    const test = await Telemetery.findOneAndUpdate(
      { link: req.params.link },
      { $inc: { 'browserType.Firefox': 1 } }
    );
    
    

    Inorder to dynamically set the field name you can do something like

    const browserName = 'Firefox';
    const key = `browserType.${browserName}`;
    const test = await Telemetery.findOneAndUpdate(
      { link: req.params.link },
      { $inc: { [key]: 1 } }
    );