回调不是函数 node.js、mongodb、res.render

Callback is not a function node.js, mongodb, res.render

我正在尝试从 MongoDB 集合中获取数据,因此我创建了一个 database.js 模块来执行此操作。该模块的功能之一是 exports.find 功能,用于从集合中查找数据。我将 callback 传递给函数,因为 Javascript 是异步的,从服务器检索数据需要时间。这是 exports.find.

的代码
exports.find = (database, table, projection, callback) => {
    MongoClient.connect(url, (err, db) => {
        if (err) throw err
        var dbo = db.db(database);
        dbo.collection(table).find({}, projection).toArray(function(err, results) {
            if (err) throw err
            callback()
            db.close()
        });
    });
}

然后我在我的 index.js 文件中使用这个函数来使用找到的数据并将其发送给客户端。我通过将 res.render 传入我的回调来做到这一点。

app.get('/', (req, res) => {
    database.find('blog', 'blog-posts', {}, res.render('pages/index'))
})

然而,每当我 运行 这个时,我都会得到这个错误

TypeError: callback is not a function
    at C:\UsersSwag\Documents\Coding\Blog\database.js:23:13

调用回调时错误指向database.js文件

callback()

有谁知道如何解决这个问题?任何帮助将不胜感激。

你的回调不是一个函数,因为你已经在 database.find 中调用它,然后试图调用所述函数的 return 值作为你的回调。

也许这会有所帮助:

const one = () => console.log(1)

const cbTest = (cb) => cb()

cbTest(one()) // Error: cb is not a function as it already returned 1

cbTest(one) // will console.log 1 as it is invoked correctly 

通常回调作为匿名函数传递,如下所示:

database.find('blog', 'blog-posts', {}, () => res.render('pages/index'))

您可以在 MongoClient.connect function/method 中看到相同的模式。第二个参数是以 (err, db) 为参数的匿名回调。