Search code examples
javascriptnode.jsmongodbmongodb-querymongodb-update

MongoDB increment a variable in a subobject


i want to increment a variable located in a subobjcetc of a mongodb database.

This is my code:

let collection = mongoose.db("wars").collection("servers")
collection.findOneAndUpdate({"id": message.guild.id}, {$inc: {"starship.$.": 1}})

In "starship" object there are some other fields, all with a integer as value.
What i need to do is update a fields from a variable.

Example:

let example = "test"
let collection = mongoose.db("wars").collection("servers")
collection.findOneAndUpdate({"id": message.guild.id}, {$inc: {"starship.$." + example: 1}})

But the "+" give an error, because i cannot access to the field from a variable.
I tried also with starship.$.${example}, but isn't working.
How i can do?

Thanks in advice for help and sorry for bad english!


Solution

  • You can create a new object and put that in MongoDB query, For example:

    let example = "test";
    let newObject={};
    newObject["starship.$." + example] = 1;
    let collection = mongoose.db("wars").collection("servers");
    collection.findOneAndUpdate({"id": message.guild.id}, {$inc: newObject});