Nodejs MongoDB 本机驱动程序不显示文档

nodejs mongodb native driver not display docs

本文关键字:显示 文档 驱动程序 MongoDB 本机 Nodejs      更新时间:2023-09-26

下面的代码有问题吗?

昨天使用相同的代码,将带有文档的结果返回给我,今天它不起作用.....

有没有更好的方法来编写此代码?

var mongodb     = require('mongodb'),
    MongoClient = mongodb.MongoClient,
    url         = 'mongodb://localhost/api';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
    if (err) {
        console.log('Unable to connect to the mongoDB server. Error:', err);
    } else {
        console.log('Connection established to', url);
        db.close();
    }
});
exports.findAll = function(req, res) {
    MongoClient.connect('mongodb://localhost/api', function(err, db) {
        console.log(db);
        var collection = db.collection(req.params.section);
        collection.find().toArray(function(err, items) {
            res.send(items);
        });
        db.close();
    });
};

根据此页面,您在find返回代码中的结果之前关闭db,请尝试将db.close()放入find的回调中

    collection.find().toArray(function(err, items) {
        res.send(items);
        db.close();
    });

由于数据库的异步性质,看起来您在查询返回文档之前正在关闭数据库。 这是一个争用条件,根据事件的顺序,它的性能可能会有所不同。 在关闭数据库之前,必须确保已完成查找查询。

collection.find().toArray(function(err, items) {
    res.send(items);
    db.close();
});

这样,您将在回调中关闭数据库,该回调仅在查询完成时执行。