Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

296
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda