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); } }); });
- 快速请求被调用两次
- 如何解决Azure中的500.1002错误?
- Eclipse中的Node Express Project的JavaScript文件中没有定义'angular'
- 用于“传统”站点的Node.js
- 检查用户是否使用PassportJS / ExpressJSlogin
- 如何在Node.js / Express中redirect(301)?
- 如何使用node.js,Express和knox从浏览器上传文件到Amazon S3?
- Phonegap在服务器端使用expressjs和passportjs进行身份validation
- 当express.static(__ dirname)函数在node.js中使用express时,redirect到错误的html页面