find()结果到数组,但不使用.filter的node.js mongodb

我试图从mongodb.find()返回结果使用Array.filter() mongodb.find() ,但它不工作!
我得到这个错误:

(TS)属性“filter”在types“{}”上不存在。

 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 } 

你的代码中的主要问题是你使用asynchronous函数,作为一个常规的函数,它返回一个结果。 asynchronous函数返回一个承诺,或接受callback,asynchronous操作完成时调用。 callback产生callback地狱,所以它更好地使用承诺或async/awaitfunction,在ES7中添加。

固定的代码,可能看起来如此:

 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,所以要使用结果调用代码,你应该创build一个promise链:

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