簡體   English   中英

MongoDB:Collection.Find()是否支持promise

[英]MongoDB : does Collection.Find() support promise

我正在嘗試改造舊的Node.js Web服務,以用鏈式Promise代替回調函數。 查詢mongodb時,我們使用以下語法遍歷結果集。

collection.find(filter).toArray(function(err, items) {
          if (err) {
            throw(err);
          } else {
            console.log(items);

          }       

如果我嘗試更換.toArray()與部分.then()我收到以下錯誤:“col.find(...),然后是不是一個函數”。

如果我將.find()替換為.findOne().then() ,則代碼可以正常工作。

任何幫助表示贊賞。

find返回一個Cursor ,但是光標的toArray方法返回一個promise。 因此,您可以執行以下操作:

collection.find(filter).toArray().then(...)

我假設您正在使用mongoosejs。

collection.find()只是一個查詢。 為了使它執行並返回一個promise,您需要在其上調用.exec()。

collection.find(filter).exec()
    .then(items => console.log(items))
    .catch(err => { // handle error })

貓鼬文檔為您提供了有關如何在回調或Promise中使用貓鼬的更多詳細信息: https : //mongoosejs.com/docs/api.html#model_Model.find

暫無
暫無

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

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