如何使用mongodb(建立原型,连接数据库)

  前两天看了一个朋友做的mongodb数据库,他是自己从某网络大学试听课学的,从可读性和模块区分方面做的比较差,所以写下此文,以作交流.

  首先是创建一个modules文件夹,这里面用来存放mongodb数据原型,把user,admin等数据暴露给index.js.以下做示例

  先创建一个user原型

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({ //用户名(必传),密码(必传),头像(必传),电话,邮箱
  username: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  coverImg: {
    type: String,
    required: true
  },
  phone: Number,
  email: String,
}, {
  timestamps: true
})
const User = mongoose.model('user', UserSchema);
module.exports = User;//暴露User

  创建完成需要的原型之后,全部引入到index.js文件中

const mongoose = require('mongoose');
const ProductType = require('./products_type');
const Product = require('./products');
const User = require('./user');
const Star = require('./star');
const Comment = require('./comment'); //评论
const Admin = require('./admin');


//本地数据库

// mongoose.connect('mongodb://localhost:27017/test', {
//     useNewUrlParser: true
//   })
//   .then(
//     console.log('连接本地服务器成功')
//   ).catch(err => console.log(err));


// 远程数据库
const uri = "mongodb+srv://管理员:密码@cluster0-3jl2x.mongodb.net/test?retryWrites=true";
mongoose.connect(uri, {
    useNewUrlParser: true,
    dbName: '数据库名称'
})
.then(() => {
    console.log('连接远程数据库成功')
})
.catch(err => console.log(err));

module.exports = {
  ProductType,
  Product,
  User,
  Star,
  Comment,
  Admin,
}

  之后就是在routes文件夹中对路由进行设置,以admin为例,该文件处于routes>api>v1>admin>index.js

  

// get post put delete
const router = require('express').Router();
const bcrypt = require('bcryptjs');//加密
const { ProductType,Admin } = require('../../../../modules');
const jwt = require('jsonwebtoken'); // 对jwt数据进行加密处理
const {
  jwtSecret,adminId
} = require('../../../../utils/config');//引入密令,超级管理员id


router.post('/admin_reg', async (req, res) => { //注册管理员

  const token = req.headers.authorization.split(' ')[1]; // 获取token
  const decoded = jwt.verify(token, jwtSecret);
  const {
    userId
  } = decoded;
  if (userId != adminId) {
    res.json({
      status: "error",
      info: "超级管理员才有注册权限"
    })
    return;
  }
  if (!req.body.username) {
    res.json({
      status: 'error',
      info: '用户名不能为空'
    })
    return;
  }
  const userCount = await Admin.countDocuments({
    username: req.body.username
  })

  if (userCount > 0) {
    res.json({
      status: 'error',
      info: '用户名已存在'
    })
  } else {
    try {
      var user = req.body;
      // 用户密码加密处理
      const salt = bcrypt.genSaltSync(10);
      const pwd = bcrypt.hashSync(req.body.password, salt);
      user.password = pwd;
      const admin = new Admin(user);
      const result = await admin.save()
      res.json({
        status: 'success',
        info: '注册成功' + result
      })
    } catch (err) {
      res.json({
        status: 'error',
        info: err
      })
    }

  }
})



//查询管理员信息
router.get('/manager_info', async (req, res, next) => {
  try {
    const token = req.headers.authorization.split(' ')[1]; // 获取token
    const decoded = jwt.verify(token, jwtSecret);
    const {
      userId
    } = decoded;
    const user = await Admin.findById(userId);
    res.json(user);
  } catch (err) {
    next(err);
  }
})


router.delete('/delete', async (req, res) => { //删除管理员
  try {

    const token = req.headers.authorization.split(' ')[1]; // 获取token
    const decoded = jwt.verify(token, jwtSecret);
    const {
      userId
    } = decoded;
    if (userId != adminId) {
      res.json({
        status: "error",
        info: "只有超级管理员才有删除管理员权限"
      })
      return;
    }
    if (!req.query.username) {
      res.json({
        status: 'error',
        info: '用户名不能为空'
      })
      return;
    }
    const check = await Admin.findOne({
      username: req.query.username
    })
    if (check == null) {
      res.json({
        status: 'error',
        info: '未查询到该管理员'
      })
      return;
    }
    if (check.id == adminId) {
      res.json({
        status: 'error',
        info: '无法删除超级管理员'
      })
      return;
    }
    await Admin.deleteOne({
      username: req.query.username
    });
    res.json({
      status: 'success',
      info: "删除成功"
    })
  } catch (err) {
    res.json({
      status: 'error',
      info: err
    })
  }
})



module.exports = router;

  以上就是对于mongodb数据原型的建立以及基本处理,希望能帮到大家

  

原文地址:https://www.cnblogs.com/gitByLegend/p/10714949.html