0

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.

  • You cannot return something *now* that will arrive in the future just as you can't read tomorrows newspaper. – Jonas Wilms Jun 14 '18 at 20:42
  • @JonasW. Thank you for the link, I now know that mongoose queries are promise-like (which I did not know before and explains a lot). However going through what was talked about in the link and other conversations here I can only manage to get it to return a promise object or errors about unhandled promise errors. None of these really help me to get to what I need, which is I just need to understand how to output the number I've incremented here. Is there a simpler way to do this? I'm still learning and will continue to read up on these asynchronous calls but I really just need that number. – twilhite Jun 14 '18 at 21:51
  • You can't read tomorrows newsaper!! Accept that. – Jonas Wilms Jun 15 '18 at 05:06
  • @JonasW. I fully accept that. But currently I don't have access to any newspapers. Telling me I can't read tomorrow's paper doesn't help me read today's newspaper, it just tells me what I can't do. Telling me I can't use my current solution doesn't solve my problem, it just tells me I don't know the answer. – twilhite Jun 15 '18 at 18:11

0 Answers0