【问题标题】:node.js mongodb find() results to array but not use .filternode.js mongodb find() 结果到数组但不使用 .filter
【发布时间】:2017-09-08 19:13:10
【问题描述】:

我尝试对从mongodb.find() 返回的结果使用Array.filter(), 但它不起作用!
我收到此错误:

(TS) 类型“{}”上不存在属性“过滤器”。

function find(collectionName: string, filter: any = {},callback: Function) {
    const MongoClient = require('mongodb').MongoClient;
    let url = "mongodb://localhost:27017/test";

    MongoClient.connect(url, function (err, db) {
        if (err) {
            callback(err, null);
            //throw err;
            db.close();
        } else {
            let rs = db.collection(collectionName).find(filter, { _id: false });

           rs.toArray(function (err, result) {
                if (err) throw err;
                callback(null,  result);
                db.close();
            });               

        }

    });//MongoClient

}

【问题讨论】:

    标签: javascript node.js mongodb typescript


    【解决方案1】:

    您的代码中的主要问题是,您使用异步函数作为常规函数,它返回一个结果。异步函数返回一个 Promise 或接受回调,它在异步操作完成时调用。回调会产生回调地狱,因此最好使用 ES7 中添加的 Promise 或 async/await 功能。

    固定的代码,可能是这样的:

    function find(collectionName: string, filter: any = {}) {
        const MongoClient = require('mongodb').MongoClient;
        let url = "mongodb://localhost:27017/test";
    
        return MongoClient
          .connect(url)
          .then(db => db.collection(collectionName).find(filter, { _id: false }))
          .then(rs => rs.toArray())
          .finally(() => db.close());
    }
    

    请注意,目前find函数不接受callback参数,它返回一个promise,所以要在调用代码中使用result,你应该创建一个promise链:

    find(...)
      .then(results => // TODO: use results here)
      .catch(err => // TODO: process error here);
    

    【讨论】:

      猜你喜欢
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 2019-02-15
      • 1970-01-01
      • 2017-02-11
      • 2018-08-02
      • 2016-05-12
      相关资源
      最近更新 更多