Node.js+Express+MongoDB随手DEMO

宦博雅
2023-12-01

Node.js+Express+MongoDB随手DEMO

MongoDB的操作

引入模块mongoose 便于操作。
数据库连接

// dbconnect.js
var mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/exercise");
 var db = mongoose.connection;

db.on("error",function (error) {
    if(error)
    console.log(error);
    }
    );
db.on("open",function () {
    console.log("数据库连接成功 ")
})
module.exports = db;

定义一个user Schema便于存储用户的id和password

-----user.js-------
var mongoose = require('mongoose');
var dbconnect = require('../DB/dbconnect.js');

var Schema = mongoose.Schema;
var userSchema = new Schema({
   id: String,
   password:String
},{
   versionKey: false
});

module.exports = mongoose.model('user',userSchema);

用户注册处理

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var user = require('../DB/user.js');
var mongoose = require('mongoose');

router.post('/singup',function (req,res,next) {
    console.log(req.body);
    var id  = req.body.id;
    var password = req.body.password;
   var users = new user ({
       id:id,
       password:password
   });
  users.save(function (err, res) {

      if (err) {
          console.log("Error:" + err);
      }
      else {
          console.log("Res:" + res);
      }
  })

})

登陆操作处理

router.post('/login',function (req,res,next) {

    var username = req.body.username;
    var password = req.body.password;
    user.find({id:username},function (err,result) {
        if(!result[0]){
            res.send('用户不存在');
            console.log('id'+err)
        }
        else{
            if(result[0].password == password)
            {
                res.send('success')
            }
          else{
             res.send('密码错误');
                console.log('password'+err);
            }
        }
    })
});
//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 bodyParser = require('body-parser');
var router = require('./routes/router');
var handle = require('./routes/handle');
var monggose = require("mongoose");
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(router);
app.use(handle);
// 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;

 类似资料: