簡體   English   中英

nodejs mongodb本機驅動程序不顯示文檔

[英]nodejs mongodb native driver not display docs

下面的代碼有問題嗎?

昨天使用相同的代碼,將文檔結果返回給我,今天卻不起作用.....

有沒有更好的方法來編寫此代碼?

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

在此頁面上 ,請先關閉db然后在find返回代碼中的結果之前,請嘗試將db.close()放入find的回調中

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

由於數據庫具有異步特性,因此看起來您在查詢返回文檔之前就關閉了數據庫。 這是一個競賽條件,根據事件的順序,它的執行可能會有所不同。 在關閉數據庫之前,必須確保已完成find查詢。

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

這樣,您將關閉回調中的數據庫,該回調僅在查詢完成后才執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM