下面是一个完整的mongodb数据库的增删改查,请忽略js
//view
indexq.ejs 前台首页
Bootstrap 101 Template
标题:
类别:
作者:
//后台主页index
大气网站后台模板
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();//生成一个express实例 app。
var session = require("express-session");
// view engine setup
//设置 views 文件夹为存放视图文件的目录, 即存放模板文件的地方,__dirname 为全局变量,存储当前正在执行的脚本所在的目录。
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');//设置视图模板引擎为 ejs。
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());//加载解析cookie的中间件。
app.use(express.static(path.join(__dirname, 'public')));//设置public文件夹为存放静态文件的目录。
//session
app.use(session({
secret: 'recommend 128 bytes random string',
cookie: { maxAge: 20000 * 60 * 1000 },
resave: true,
saveUnintialized: true
}))
//路由控制器。
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
路由routes
index.js
var express = require('express');
var router = express.Router();
var mongo = require("mongodb").MongoClient;
var url1 = "mongodb://localhost:27017/mydb";
var async=require('async')
var ObjectId=require('mongodb').ObjectId;
/* GET home page. */
//用户名存储
router.get('/', function(req, res, next) {
res.render('index', {name:req.session.name});//render渲染
console.log(req.session.name)
});
//退出销毁用户名
router.get('/xiaohui', function(req, res, next) {
req.session.destroy(function(err){
if(err){
console.log(err)
}else{
res.redirect("/")
}
})
});
router.get('/news', function(req, res, next) {
var count = 0;
var page = 0;
var size = 5;
//页码
var pagenum = req.query.pagenum;
var pagenum = pagenum?pagenum:1;
mongo.connect(url1,function(err,database){
database.collection("news1",function(err,coll){
//异步处理
async.series([
function(callback){
coll.find({}).toArray(function(err,data){
count = data.length;//数据条数
//page = page<1? 1:page;
page = Math.ceil(count/size);//总共的页数
pagenum = pagenum<1?1:pagenum;//页码小于1;显示1
pagenum = pagenum>page?page:pagenum;//页码大于总页数;显示总页数
callback(null,'')
})
},function(callback){
coll.find().sort({_id:-1}).limit(size).skip((pagenum-1)*size).toArray(function(err,data){
callback(null,data)
})
}
],function(err,data){
res.render('news',{list:data[1],page:page,count:count,pagenum:pagenum,size:size})
database.close()
})
// if(err) throw err
// coll.find().sort({_id:-1}).toArray(function(err,data){
//
// res.render('news',{list:data});//render渲染
// database.close()
// })
})
})
});
//新闻数据传页面
router.get('/indexq', function(req, res) {
res.render('indexq', { });//render渲染
});
router.get('/login', function(req, res) {
res.render('login', { });//render渲染
});
router.get('/input', function(req, res) {
res.render('input', { });//render渲染
});
router.get('/alert', function(req, res) {
res.render('alert', { });//render渲染
});
module.exports = router;
user.js
var express = require('express');
var router = express.Router();
var mongo = require("mongodb").MongoClient;
var url1 = "mongodb://localhost:27017/mydb";
var ObjectId=require('mongodb').ObjectId;
/* GET users listing. */
router.get('/', function(req, res, next){
});
//前端首页注册
router.post('/indexq', function(req, res){
// console.log(req.body)
mongo.connect(url1,function(err,database){
database.collection("users",function(err,coll){
// console.log(coll)
coll.find({name:req.body.name}).toArray(function(err,data){
// console.log(data)
//console.log(req.body);
if(data.length>0){
res.send("2")
database.close()
}else{
coll.insert(req.body,function(){
res.send("1")
database.close()
})
}
})
})
})
});
//登录
router.post('/login', function(req, res){
console.log(req.body)
mongo.connect(url1,function(err,database){
database.collection("users",function(err,coll){
// if(err) throw err
coll.find({"name":req.body.user,"pass":req.body.pass}).toArray(function(err,data){
console.log(data)
if(data.length>0){
req.session.name = data[0].name;
//console.log(data[0].user)
res.send("1")
database.close()
}else{
res.send("2")
database.close()
}
})
})
})
});
//前端页面提交
router.post('/input', function(req, res){
// console.log(req.body)
mongo.connect(url1,function(err,database){
database.collection("news1",function(err,coll){
// console.log(coll)
coll.find({name:req.body.biaoti}).toArray(function(err,data){
//console.log(data)
//console.log(req.body);
if(data.length>0){
res.send("2")
database.close()
}else{
coll.insert(req.body,function(){
res.send("1")
database.close()
})
}
})
})
})
});
//删除数据
router.post('/shanchu', function(req, res){
//console.log(req.body.biaoti)
//console.log(req.body)
mongo.connect(url1, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var whereStr = {"biaoti":req.body.biaoti}; // 查询条件
//console.log(whereStr)
dbo.collection("news1").deleteOne(whereStr,function(err, obj){
if (err) throw err;
console.log("文档删除成功");
res.send("1")
db.close();
});
});
});
//修改数据
router.post('/xiugai', function(req, res){
//console.log(req.body)
mongo.connect(url1, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");//选择数据库名字
var yuanlai = {"biaoti":req.body.biaoti,"leibie":req.body.leibie,"zuozhe":req.body.zuozhe}; // 查询条件
var updateStr = {$set: {"biaoti":req.body.biaoti1,"leibie":req.body.leibie1,"zuozhe":req.body.zuozhe1}};
//console.log(yuanlai,updateStr)
dbo.collection("news1").updateOne(yuanlai, updateStr, function(err, data) {
if (err) throw err;
console.log("文档更新成功");
res.send("1")
db.close();
});
});
});
//查询
router.post('/chaxun', function(req, res){
var whereStr = req.body.biaoti
mongo.connect(url1, function(err, db) {
var dbo = db.db("mydb");
// 查询条件
dbo.collection("news1").find({$or:[{biaoti:whereStr},{leibie:whereStr},{zuozhe:whereStr}]}).toArray(function(err, result) {
console.log(result)
if(result.length){
res.send(result);
}else{
res.send("0")
}
db.close();
});
});
});
module.exports = router;