-2

我有一个为维护而创建的集合ticket_no,其文档如下所示,

{
  id:"TICKET_ID",
  TICKET_NO:7
}

现在,当我尝试为 a 查找 OneAndUpdate 时ticket_id,以 1 递增TICKET_NO

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;
}

该函数返回null值而不是ticket no

4

1 回答 1

0

您在 ret 中得到的是 findOneAndUpdate 函数对象,而不是您的实际文档。

您需要收听回调或使用 async/await 以使值在那里,

尝试其中之一,

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
}

或者,

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
            }
          });
     );
}
于 2020-03-14T11:47:55.027 回答