Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

294
Views
How To Update One Mongo Documents Node.js based on string input?

I have the async function below. DeviceStatus is a Mongo Collection of devices which has the property SerialNumber defined and NumberOfRetries defined. I want to take in as an input a serialNumber and retries. serialNumber is a string that is known to be in the collection. retries is a string representing an int less than 10. In the async function below I'd like to read the retries value, add 1 to it and then update the mongo document with the same serialNumber

static async incrementNumberOfRetries(serialNumber, retries){
  const retriesInt = parseInt(retries);
  const accumulatedRetriesInt = retriesInt + 1;
  const accumulatedRetriesString = accumulatedRetriesInt.toString();
  try {
    await DeviceStatus
      .updateOne({
        "SerialNumber": serialNumber
        },
        {
          $set: {
            "NumberOfRetries" : accumulatedRetriesString
        }
      })
  } catch(error) {
    console.log(error)
  }
}

I'm not entirely sure what I'm doing wrong here. I know the first 3 lines are correct and there's no error being caught. But the NumberOfRetries is not being set properly in the collection. Initially, it's been set to 1 so I've tested this function and the value is not changing. Is there something wrong with how I'm using updateOne? How can I pass in a variable to perform the update?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

To increment the numberOfRetries, you can use MongoDB update operator $inc.

DeviceStatus.update({
    serialNumber,
  },
  {
    $inc: {
      numberOfRetries: 1
  }
})

See a working example here on MongoDb Playground

Your code should look like this

static async incrementNumberOfRetries(serialNumber, retries){
  try {
    await DeviceStatus
      .update({
        "SerialNumber": serialNumber
        },
        {
          $inc: {
            "NumberOfRetries" : 1
        }
      })
  } catch(error) {
    console.log(error)
  }
}

Check out the docs for the $inc operator here

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!