3. 在app.js中,不要忘了声明用到的模块:
var users = require('./routes/users'); //用户接口
app.use('/users', users); //在app中注册users接口
4. 在index.ejs下,添加:
后台接口调用:<a href="http://localhost:3000/users/getUserInfo?id=1">getUserInfo</a>
5. 在画面中点击getUserInfo链接,可以看到返回结果:
六. 使用Node.js+MongoDB,实现增删改查:
这个例子是基于上面的接口实例,通过前台页面使用jquery异步调用node.js接口的方式实现的。
1. 项目结构说明:
先说明一下MongoDB的结构,
DB名:sun

Collection有两个,test和other,test中保存name和age,other中保存name和job。
把他们分开是为了说明async.map的时候更方便。
这里会详细说明一下查询find的实现,增删改相对容易。
在创建Collection的时候,可以指定唯一索引。默认是只有id唯一。
db.collection.createIndex( <key and index type specification>, { unique: true } )
例:(将test中的name设为唯一索引)
db.test.createIndex({name:1},{unique:true})
下面是两个Collection里面准备的数据,在新增做好以后就可以自己插入了。
项目结构如下:
新增:
routes/mongodb/find.js<- 查询
routes/mongodb/insert.js ??<- 新增
routes/mongodb/update.js <-更新
routes/mongodb/delete.js ??<-删除
routes/mongodb/collectionTest.js <-Collection对象
routest/sun.js ??<-sun.ejs对应的js文件(类似于index.js)
views/sun.ejs ??<-页面(类似于index.ejs)
2. collectionTest.js:
function CollectionTest() {
this.id;
this.name;
this.age;
this.job;
}
module.exports = CollectionTest;
3. find.js:
var mongodb = require('mongodb')
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/sun';
var URL = require('url');
var CollectionTest = require('./collectionTest');
var express = require('express');
var router = express.Router();
var async = require('async');
var selectData = function(client, params, callback) {
//连接到表
var db = client.db('sun');
var collectionTest = db.collection('test');
var collectionOther = db.collection('other');
//查询数据
var whereStr;
if (params.name) whereStr = {"name" : params.name};
collectionTest.find(whereStr, function(error, results){
if (error) throw error;
results.toArray(function(err, arr){
if (error) throw error;
// async.map会将循环处理完以后,统一执行callback而不像其他异步调用执行分别执行
async.map(arr, function(item, callback){
var whereStr = {"name": item.name};
collectionOther.find(whereStr, function(error, result){
result.toArray(function(err, arrJob){
console.log(arrJob);
console.log("------------------------");
if (arrJob){
item.job = arrJob[0].job;
console.log(item);
console.log("*************************");
}
callback(null, item);
});
})
}, function(err, result){
// result是上表面item组成的数组
callback(result);
})
});
});
}
router.get('/find', function(req, res, next){
var params = URL.parse(req.url, true).query;
MongoClient.connect(DB_CONN_STR, function(err, client) {
console.log("连接成功!");
selectData(client, params, function(result) {
res.send(JSON.stringify(result));
client.close();
console.log("连接断开!");
});
});
})
module.exports = router;
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/shumachanpin/article-74050-6.html
乱放屁
核潜艇国之利器