Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 回调函数不是node.js、mongodb、res.render函数_Javascript_Node.js_Mongodb_Callback - Fatal编程技术网

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

Javascript 回调函数不是node.js、mongodb、res.render函数,javascript,node.js,mongodb,callback,Javascript,Node.js,Mongodb,Callback,我试图从MongoDB集合中获取数据,因此我创建了一个database.js模块来实现这一点。模块上的函数之一是exports.find函数,用于从集合中查找数据。我将回调传递到函数中,因为Javascript是异步的,从服务器检索数据需要时间。这是exports.find的代码 exports.find = (database, table, projection, callback) => { MongoClient.connect(url, (err, db) => {

我试图从MongoDB集合中获取数据,因此我创建了一个database.js模块来实现这一点。模块上的函数之一是exports.find函数,用于从集合中查找数据。我将回调传递到函数中,因为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'))
})
callback()
然而,每当我运行这个程序时,就会出现这个错误

TypeError: callback is not a function
    at C:\Users\21Swag\Documents\Coding\Blog\database.js:23:13
调用回调时,错误指向database.js文件

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

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

您的回调不是函数,因为您已经在database.find中调用了它,然后尝试调用所述函数的返回值作为回调

app.get('/', (req, res) => {
    database.find('blog', 'blog-posts', {}, res.render('pages/index'))
})
callback()
也许这会有帮助:

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函数/方法中看到相同的模式。第二个参数是以(err,db)为参数的匿名回调。

如果要将参数传递给函数,该怎么办。例如,我想使用res.render将结果发送到客户端。要做到这一点,我不需要在exports.find函数中调用res.render('pages/index',results)?将其包装到另一个函数中,而不调用它。我更新了我的答案。谢谢你的回答。它帮了我很多忙。没问题,很高兴我能帮上忙。你能接受这个答案吗?:)