2017-04-20 90 views
1

我試圖從MongoDB中加載數據到我的express,最終在我的html中使用angular來顯示。現在我已經得到它的數據,但這隻適用於數據庫中的一條記錄。如果我創建多個記錄,它給在控制檯以下錯誤:從MongoDB獲取數據

「後,他們被送到不能發送頭」

這是我的特快「取」請求:

router.get('/getdata', function(req, res, next){ 
var findDocuments = function(db, callback) { 
var cursor = db.collection('userdata').find({}); 
cursor.each(function(err, doc) { 
    assert.equal(err, null); 
    if (doc != null) { 
    res.status(200).json(doc); 
    } else { 
    callback(); 
    } 
}); 
}; 
    mongo.connect(url, function(err, db) { 
    assert.equal(null, err); 
    findDocuments(db, function() { 
    db.close(); 
    }); 
}); 
    console.log('Items have been returned'); 
}); 
+0

首先,我會建議使用Mongoose,它提供了非常好的附加功能來與MondoDB一起工作。創建模式後,您可以通過簡單的一個mongoose方法mySchema.find(err,response)來獲取所有現有的對象。並用貓鼬,你將不需要打開和關閉連接「手動」 – JavaEvgen

+0

不使用循環來檢查空文檔,把條件放在發現像find({{key:{$ exists:true}}) –

回答

0
router.get('/getdata', function(req, res, next){ 

    var findDocuments = function(db, callback) { 

    //use such codtion that filter null/empty doc 
    //replace key with field of your doc 
    var cursor = db.collection('userdata').find({'key' : {$exists : true}}); 

    //return all docs 
    if(cursor){ 
    return callback(cursor); 
    }else{ 
    return callback([]); 
     } 

    }; 

    mongo.connect(url, function(err, db) { 
    assert.equal(null, err); 
    findDocuments(db, function(docs) { 
    db.close(); 

    //send finaly doc here 
    console.log(docs); 
    res.status(200).send(docs); 

    }); 
}); 

    console.log('Items have been returned'); 
}); 
+0

這不起作用爲了我。它在控制檯中返回一個錯誤:TypeError:將循環結構轉換爲JSON – Larsmanson

+0

根據文檔模式或mongo驅動程序在發送或更改查找條件之前使用console.log檢查文檔 –