I am having a problem with getting a function to work and have been searching for 2 days and can't quite find the answer to this question. I think there is something I am not understanding about mongoose/mongodb queries in nodejs.
I have a function which increments a mongodb document so I can create sequential codes for items we are creating.
function getNextUpc(sequenceName){
var query = {"_id": sequenceName};
var update = {$inc:{sequence_value:1}};
var options = {new: true};
Counter.findOneAndUpdate(query, update, options, function(err, counter){
if(err){
console.log(err);
} else {
console.log(counter.sequence_value); // gives updated number
return counter.sequence_value // gives undefined
}
});
};
I would like for this function to return the newly incremented value when I call the function in my route with getNextUpc('productupc')
. Currently it is incrementing correctly and I can console.log the correct value, but if I try to return the value it comes out as undefined.
Returning the value from outside the callback also does not work, so I know I am not understanding something about this setup but I have been poring over the documentation and I just can't seem to figure out what I'm doing wrong. Thanks in advance for the help and if anyone has some links on where to read so I can better understand what's going on here I would greatly appreciate it.