Firdous Firdous - 4 months ago 17
Node.js Question

Simple mongo object upsert using strongloop

I am trying to do a simple upsert operation on a particular record where the field to be updated is a number type.
I fetch the record using its record id, just +1 the number field and save it again, but for some reason it wont increment/update as seen from the log

The code is:

customer.findById(customerObject.id, function(err, objectResult){

console.log(objectResult.imageIndex);

if(!objectResult.imageIndex){
objectResult.imageIndex = 1;
}
else{
var index = objectResult.imageIndex;
objectResult.imageIndex = index++;
console.log(objectResult.imageIndex);
}

customer.upsert(objectResult, function(err, response){});
})


Both the console.log would display same value.. why wont it increase and update, any thing wrong with the code?

Answer

The issue is with the statement:

objectResult.imageIndex = index++;

This is because index++ does the assignment first and then increments the value of index.

It should be either:

objectResult.imageIndex = ++index;

or

objectResult.imageIndex = index + 1;