-2

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

Nilesh Singh
  • 1,750
  • 1
  • 18
  • 30
Sufail Kalathil
  • 558
  • 6
  • 21

1 Answers1

0

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
            }
          });
     );
}
Nilesh Singh
  • 1,750
  • 1
  • 18
  • 30
  • both methods are working.but TICKET_NO on the sequence collection is not updating always getting the same ticket no. Kindly help to resolve the same – Sufail Kalathil Mar 14 '20 at 15:15
  • What is the. TICKET_NO that you're getting? – Nilesh Singh Mar 14 '20 at 15:20
  • `{id:"TICKET_ID", TICKET_NO:7 }`.. ticket_no should be increment by 1 on each call.unfrtntly it is not updating on the database. so function always return 7 as ticket_no – Sufail Kalathil Mar 14 '20 at 15:33
  • Updated answer to reflect changes. Your options, i.e, `new: true` was not valid, as it was not in the correct format. The changes should work. – Nilesh Singh Mar 14 '20 at 16:13