mongoskin是一个操作MongoDB的模型工具 相当于数据库类 与之相当的还有mongoose比较出名
安装模块(特地加了版本,这里被坑过,在Ubuntu中开发的好好的,部署到线上centos中mongodb模块最新版是3.0.0,因此和mongoskin不匹配,所以特别指定版本安装)
npm install mongodb@2.2.33
npm install mongoskin@2.1.0
导入mongoskin 连接MongoDB中test数据库
var mongo = require('mongoskin'); var db = mongo.db("mongodb://localhost:27017/test", {native_parser: true});
操作与MongoDB原生语法大同小异 只不过多了回调
增
router.post('/doadd', function (req, res, next) { var param = req.body; if(param.username && param.password){ //插入数据 db.collection('user').insert({'username': param.username,'password':param.password}, function (err, result) { db.close(); if(!err){ res.send({'status':1}); }else{ res.send({'status':0}); } }); } });
删
router.post('/dodel', function (req, res, next) { var param = req.body; if(param.id){ var ObjectId = mongo.ObjectID; db.collection('user').remove({'_id':ObjectId(param.id)}, function (err, result) { db.close(); if(!err){ res.send({'status':1}); }else{ res.send({'status':0}); } }); } });
改
router.post('/doedit', function (req, res, next) { var param = req.body; if(param.username && param.password){ var ObjectId = mongo.ObjectID; //修改单条数据 db.collection('article').update({'_id':ObjectId(param._id),'username':param.username},{$set:{'password': param.password}}, function (err, result) { db.close(); if(!err){ res.send({'status':1}); }else{ res.send({'status':0}); } }); } });
查
router.get('/', function (req, res, next) { db.collection('article').find().toArray(function (err, result) { db.close(); res.render('admin/index', {title: '后台管理',result:result}); }); });