nodejs mongodb本机驱动程序不显示文档

时间:2016-02-18 13:45:20

标签: javascript node.js mongodb

下面的代码有问题吗?

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

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

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();
    });
};

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

由于数据库的异步特性,在查询返回文档之前,您似乎正在关闭数据库。这是一种竞争条件,根据事件的顺序,它可能会有不同的表现。在关闭数据库之前,必须确保已完成查找查询。

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

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