2015-10-06 32 views
2

我将我的数据库连接转换为MongoClient,并且难以更改我以前的代码部分。Nodejs Express 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复制这种行为。我建立了连接,并且可以查询数据库,但是返回集合,并按照上面的方法循环遍历每个文档不起作用。

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

回答

1

从你的解释,我知道你要使用本机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); 

     } 
    }); 
});