簡體   English   中英

如何使用nodejs查找和更新mongodb中的最新記錄?

[英]How to find and update the latest record in mongodb using nodejs?

我的 mongodb 包含重復記錄,我想更新最新記錄。 所以我嘗試排序標准如下。

modelname.findOneAndUpdate(filter, {$set: options },async function(err,result){
  if(err)
     next(err)
  else{
   console.log("updated");
  }
  }).sort({createdAt: -1})

在這里,我嘗試使用 createdAt 進行排序,但我無法更新最新記錄。 請幫助我哪里出錯了。

如果我嘗試打印結果。

  result ------- :  { _id: 5e047b81115fcff2d7f55507,
                      BatchId: '1577352062756',
                      ServiceCode: '1',
                      PhoneNumber: '7777777775',
                      Preset: '3',
                      Otype: 'A',
                      PType: '2',
                      Status: 'Success',
                      __v: 0,
                     createdAt: 2019-12-26T09:21:05.372Z,
                     updatedAt: 2019-12-26T10:23:28.199Z }

方法findOneAndUpdate將默認返回舊版本的文檔,當您提供 option { new: true } ,它將返回您新的、更新版本的對象

請使用具有真實值的關鍵字,然后我們將獲得更新的記錄。

modelname.findOneAndUpdate(filter, {$set: options }, { new: true },async function(err,result){
      if(err)
         next(err)
      else{
       console.log("updated");
      }
      }).sort({createdAt: -1})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM