Search code examples
node.jsmongodbmongoosemean-stackmongoose-auto-increment

Auto-Incrementing Sequence Field Mean Stack


I have a collection created for maintaining ticket_no, for which document looks like this,

{
  id:"TICKET_ID",
  TICKET_NO:7
}

Now, when I try to findOneAndUpdate for a ticket_id, incrementing TICKET_NO by 1,

function get(){
     var ret = Sequence.findOneAndUpdate(
            {
                query: { _id: 'TICKET_ID' },
                update: { $inc: { TICKET_NO: 1 } },
                new: true
            }
        );

        console.log(ret.TICKET_NO)
        return ret.TICKET_NO;
}

The function returns null value instead of ticket no


Solution

  • What you are getting in ret is the findOneAndUpdate function object, not your actual document.

    You need to listen to callback or use async/await for the value to be there,

    Try one of these,

    async function get(){
         var ret = await Sequence.findOneAndUpdate(
              { _id: 'TICKET_ID' },
              { $inc: { TICKET_NO: 1 } },
              { new: true }
         );
    
         console.log(ret.TICKET_NO) // now the ret is the doc you need
         return ret.TICKET_NO; // prints correctly
    }
    

    or,

    function get(){
         Sequence.findOneAndUpdate(
              { _id: 'TICKET_ID' },
              { $inc: { TICKET_NO: 1 } },
              { new: true },
              function(err, ret) {
                if (err) {
                  console.error(err)
                } else {
                  console.log(ret.TICKET_NO) //successful callback returns ret
                }
              });
         );
    }