Nodejs Express MongoClient收集检索

我将我的数据库连接转换为MongoClient,并且难以更改以前的代码部分。

以前,为了从集合中检索所有文档,我会使用:

$.getJSON('/users/infolist', function(data) { $.each(data, function(){ //cycles through each document and do whatever }); }); 

这将要求如下:

  router.get('/infolist', function(req, res) { var db = req.db; var collection = db.get('empcollection'); collection.find({$query: {}, $orderby: {age:1}},{},function(e,docs){ res.json(docs); }); }); 

在网上查看文档之后,我还没有想出如何使用MongoClient复制这种行为。 我已经build立连接,并且可以查询数据库,但是返回集合,并且循环遍历每个文档,如上所述不起作用。

任何意见或帮助将不胜感激。

从你的解释中,我明白你要使用本地的mongodb驱动程序从你的集合中检索一个文档列表,使用循环来更新它们,然后把它们提取到客户端:

 var MongoClient = require('mongodb').MongoClient; //Establish a connection to your database MongoClient.connect('mongodb://your/connection/string', function(err, db) { if(err) { console.log('There was an error connecting to the database'); } //Map empcollection to a variable var collection = db.collection('empcollection'); //Query the collection and retrieve the documents in an array collection.find({}).toArray(function(err, docs)) { if(err) { console.log('There was an error retrieveing the matched documents'); } //Loop through the documents and change them accordingly for(var i = 0; i < docs.length; i++) { //........ } //Retrieve the updated data res.json(docs); } }); });