2017-03-20 55 views
0

在命令行內部,我可以使用db.collection.find()顯示Mongodb集合,但我無法找到與Node中的get請求相同的內容。這裏是我的快遞路線:如何根據請求在Node.js中發送Mongodb數據

app.get('/latest/imagesearch', (req, res) => { 
    MongoClient.connect(mLab, function(err, db) { 
    if (err) { 
     console.log("Unable to connect to server", err); 
    } else { 
     console.log("Connected to server"); 

     var collection = db.collection('links'); 

     // res.send(collection.find()); 

     db.close(); 
    } 
    }); 
}); 

和數據庫信息:

{ "_id" : ObjectId("58cf0485a3c6700a3eb8b373"), "term" : "dogs", "when" : 1489962117592 } 
+0

什麼控制檯當您運行日誌報表打印快遞服務器並轉到localhost:3000/latest/imagesearch url? –

+0

嘗試:res.send(db.collection('links')。find()) – Astro

回答

1

創建集合對象後,就可以調用collection.find

app.get('/latest/imagesearch', (req, res) => { 
    MongoClient.connect(mLab, function(err, db) { 
    if (err) { 
     console.log("Unable to connect to server", err); 
     return res.send("Unable to connect to server"); 
    } else { 
     console.log("Connected to server"); 
     var collection = db.collection('links'); 
     collection.find().toArray(function(err, docs) { 
     return res.json(docs); 
     }); 
    } 
    }); 
}); 
+0

感謝這工作! – Zach

相關問題