前两天看了一个朋友做的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数据原型的建立以及基本处理,希望能帮到大家

  

如何使用mongodb(建立原型,连接数据库)的更多相关文章

  1. Java程序中与MongoDB建立连接~小记

    1.Mongo和MongoClient的关系 MongoClient继承自Mongo,使用Mongo也可建立连接,但是需要使用与Mongo适应的MongoOptions,MongoURI等类型. 2. ...

  2. mongodb 建立索引提示异常:WiredTigerIndex::insert: key too large to index, failing 1483

    { "ok" : 0.0, "errmsg" : "WiredTigerIndex::insert: key too large to index, ...

  3. MongoDB 建立与删除索引

    1.1 在独立服务器上面建立索引 在独立服务器上面创建索引,可以在空闲时间于后台建立索引. 在后台建立索引,可利用background:true参数运行 >db.foo.ensureIndex( ...

  4. MongoDB建立主从复制小案例(一主一从)

    花了两天学习了mongoDB, 今天接触到了mongo的主从配置, 把它记下来 1. 开启两个mongo服务器(用于一主一从, 没有加安全验证相关参数 : 可以使用mongd-help查看) mong ...

  5. mongodb建立索引

    创建索引 索引:以提升查询速度 语法:db.集合.ensureIndex({属性:1}),1表示升序,-1表示降序 具体操作:db.t255.ensureIndex({name:1}) db.t1.f ...

  6. PL/SQL Developer 建立远程连接数据库的配置 和安装包+汉化包+注册机

    PL/SQL Developer ,主要是讲一下如何配置PL/SQL Developer ,连接Oracle数据库. [知识点] 1.PL/SQL Developer 是什么? PL/SQL Deve ...

  7. Springboot整合mongodb时无法连接数据库

    由于之前没有接触过mongodb,最近在学习时遇到了一些问题.用yml配置mongodb如下: spring: application: name:xc-service-manage-cms data ...

  8. Node.JS + MongoDB技术浅谈

    看到一个Node.JS + MongoDB的小样例,分享给大家.魔乐科技软件学院(www.mldnjava.cn)的讲座 Node.JS + MongoDB技术讲座          云计算 +大数据 ...

  9. MFC+mongodb+nodejs 数据库的读取与写入操作

    首先通过nodejs和mongodb建立后端服务器 一.在windows平台下启动mongodb服务器 1.进入mongodb的安装目录,并进去bin目录启动mongod 2.在d盘建立mongodb ...

随机推荐

  1. linux中MTDflash设备驱动大概

    一.主要结构体 1.mtd_info,主要是描述MTD原始设备层中的设备或分区, 2.mtd_part,表示一个分区,用里面的主mtd_info和本分区mtd_info描述分区, 3.mtd_part ...

  2. scrapy爬虫框架和selenium的配合使用

    scrapy框架的请求流程 scrapy框架? Scrapy 是基于twisted框架开发而来,twisted是一个流行的事件驱动的python网络框架.因此Scrapy使用了一种非阻塞(又名异步)的 ...

  3. 【Python全栈-CSS】CSS实现网页背景图片自适应全屏

    CSS实现网页背景图片自适应全屏 功能:实现能自适应屏幕大小又不会变形的背景大图,而且背景图片不会随着滚动条滚动而滚动. 以下是用CSS实现的方法: <html> <head> ...

  4. Python004-数据处理示例:以某个数据(字段)为基准从数据中获取不同的字段行数

    数据源样式如下所示: 需求: 读取文本,以第一列为基准参考系,每个基准仅输出满足需要条数的数据:不满足,全部输出. 比如,基准为 6236683970000018780,输出条数要求为 5.若文本中含 ...

  5. Fiddler忽略捕捉大文件流

    Fiddler是款非常不错的抓包软件,可以方便的捕捉各种软件发起的HTTP请求,甚至可以在发送给服务器前或响应给应用前修改数据.但是在使用时发现,在开启Fiddler时,在浏览器中下载文件时不会马上弹 ...

  6. 前端 CSS 目录

    前端 CSS 介绍 前端 CSS语法 前端 CSS 注释

  7. C#开启异步 线程的四种方式

    一.异步委托开启线程public static void Main(string[] args){ Action<int,int> a=add; a.BeginInvoke(3,4,nul ...

  8. 学习MySQL过程中的随笔二

    MySQL深入学习:     视图 使用视图的目的:多次使用同一张临时表(或者已经存在的表) 视图只是一个虚拟表,其本质为[根据SQL语句获取动态的数据集,并为其命名],用户只需使用别名即可获得实时的 ...

  9. 基于Promise封装uni-app的request方法,实现类似axios形式的请求

    https://my.oschina.net/u/2428630/blog/3004860 uni-app框架中 安装(项目根目录下运行) npm install uni-request --save ...

  10. sping Bean 的生命周期是如何被管理

    1. 实例化一个Bean,也就是我们通常说的new 2. 按照Spring上下文对实例化的Bean进行配置,也就是IOC注入 3. 如果这个Bean实现了BeanNameAware接口,会调用它实现的 ...