前两天看了一个朋友做的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. 第七周 ip通信基础回顾

    H3C的配置指令包括:基本配置,查看指令,接口配置. 基本配置包括:查看可用指令:进入系统视图,全局配置模式:给设备命名:退回上一层模式:直接退回到用户模式. 查看指令包括:显示设备系统版本信息:显示 ...

  2. poj2688

    #include<iostream> using namespace std; #include<time.h> int m,n; ][]; ][]; typedef stru ...

  3. python基础的学习

    今日内容 1.常见操作系 1.win win7 win10 window serrer 2.linux centons 图像界面差 upuntu 个人开发(图形化较好) redhat 企业 3.mac ...

  4. 神贴真开眼界:为什么很多人倡导重视能力和素质,但同时对学历有严格要求?——代表了上一场比赛的输赢,招聘成本很重要。如果上一场游戏失败了,尽量让自己成为当前群体的尖子。学历只是其中的一个作品而已,但学历代表了学生时代为之做出的牺牲。人群自有偏向集中性 good

    对于软件工程师职位,没学历没关系,如果真觉得自己才高八斗,请在简历里附上 github项目链接或者 appstore/google play上你的作品.如果学历比别人低,那么想必是把时间和精力用在了其 ...

  5. 学号 20175201张驰 《Java程序设计》第4周学习总结

    学号 20175201张驰 <Java程序设计>第4周学习总结 教材学习内容总结 第5章 继承:避免多个类间重复定义共同行为,用我们已经有的类,去创建新的类 任何子类都可以继承它的父类的成 ...

  6. Servlet学习1

    1.首先在Tomcat的webapp目录下新建文件夹myWebapp,作为自己的web应用. 2.myWebapp下新建WEB-INF(必须这个名)目录,WEB-INF下新建classes目录放置se ...

  7. Pycharm中Python3连接Oracle

    一.环境配置:系统:win7.10 (64位)软件:1.Python3.7.2 (64位)2.instantclient-basic-windows.x64-11.2.0.4.0.zip(64位) - ...

  8. archlinux中安装Oracle12c的过程中遇到的问题

    INFO: : cannot find INFO: /usr/lib64/libpthread_nonshared.aINFO: INFO: genclntsh: Failed to link lib ...

  9. 灵雀云获邀加入CDF(持续交付基金会),成为中国区三大创始成员之一

    3月12日,在加州Half Moon Bay举行的开源领导者峰会(Open Leadership Summit 2019 )上,CDF(Continuous Delivery Foundation ) ...

  10. CentOS 7 Sersync+Rsync 实现数据文件实时同步

    rsync+inotify-tools与rsync+sersync架构的区别? 1.rsync+inotify-tools inotify只能记录下被监听的目录发生了变化(增,删,改)并没有把具体是哪 ...