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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With