一个简单的示例:
Node.js读取mongoDB并输出json数据
Node.js读取mongoDB并输出json数据
此源码是
1、读取mongoDB的数据,简单封装node mongodb Native驱动
2、包含模块如何编写
3、把JSON数据数据返回给客户端
运行此源码必须
1、安装node mongodb native驱动
2、express js框架(不安装的话简单修改index.js即可)
3、安装了mongoDB,并且有comments数据库comments collection。collection里有数据。
如果名字不一样,进index.js就可以修改。端口必须是默认的。
3、node index.js,打开127.0.0.1:8001就可以看到返回了数据
代码片段(3)
[代码] index.js
01 | var express = require( 'express' ); |
02 | var app = express.createServer(); |
03 | var db = require( './tea/db' ); |
04 | db.open({dbName: 'comments' }); |
05 | app.get( '/' , function (req,res){ |
06 | db.findOne( 'comments' ,{}, function (records){ |
07 | res.send(records); |
08 | }); |
09 | }); |
10 | app.listen(8001); |
[代码] /tea/index.js
1 | var tea = exports; |
2 | tea.hello = function (){ |
3 | console.log( 'hello world' ); |
4 | } |
[代码] /tea/db.js
01 | var mongo = require( 'mongodb' ); |
02 | var tea = tea || {}; |
03 | tea.db = exports; |
04 | tea.db.server = '127.0.0.1' ; |
05 | tea.db.port = 27017; |
06 | tea.db.db = null ; |
07 | tea.db.dbName = '' ; |
08 | tea.db.collection = '' ; |
09 | tea.db.open = function (mongoInfo,callback){ |
10 | this .dbName = mongoInfo.dbName; |
11 | if (! this .db) this .db = new mongo.Db(mongoInfo.dbName, new mongo.Server( '127.0.0.1' , 27017, {}), {}); |
12 | this .db.open( function (err,db){ |
13 | this .db = db; |
14 | if (callback) callback(db); |
15 | }); |
16 | return this ; |
17 | }; |
18 | tea.db.find = function (collection,query,callback,isFindOne){ |
19 | this .db.collection(collection, function (err, collection) { |
20 | var func = isFindOne ? 'findOne' : 'find' ; |
21 | collection[func](query, function (err,cursor){ |
22 | if (!isFindOne) { |
23 | cursor.toArray( function (err,items){ |
24 | if (callback) callback(items); |
25 | }); |
26 | } else { |
27 | if (callback) callback(cursor); |
28 | } |
29 | }); |
30 | }); |
31 | } |
32 | tea.db.findOne = function (collection,query,callback){ |
33 | this .find(collection,query,callback,1); |
34 | } |
35 | tea.db.close = function (){ |
36 | if (tea.db.db) tea.db.db.close(); |
37 | } |
38 | tea.db.hello = function (){ |
39 | console.log( 'Hello World' ); |
40 |