如何使用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数据原型的建立以及基本处理,希望能帮到大家
如何使用mongodb(建立原型,连接数据库)的更多相关文章
- Java程序中与MongoDB建立连接~小记
1.Mongo和MongoClient的关系 MongoClient继承自Mongo,使用Mongo也可建立连接,但是需要使用与Mongo适应的MongoOptions,MongoURI等类型. 2. ...
- mongodb 建立索引提示异常:WiredTigerIndex::insert: key too large to index, failing 1483
{ "ok" : 0.0, "errmsg" : "WiredTigerIndex::insert: key too large to index, ...
- MongoDB 建立与删除索引
1.1 在独立服务器上面建立索引 在独立服务器上面创建索引,可以在空闲时间于后台建立索引. 在后台建立索引,可利用background:true参数运行 >db.foo.ensureIndex( ...
- MongoDB建立主从复制小案例(一主一从)
花了两天学习了mongoDB, 今天接触到了mongo的主从配置, 把它记下来 1. 开启两个mongo服务器(用于一主一从, 没有加安全验证相关参数 : 可以使用mongd-help查看) mong ...
- mongodb建立索引
创建索引 索引:以提升查询速度 语法:db.集合.ensureIndex({属性:1}),1表示升序,-1表示降序 具体操作:db.t255.ensureIndex({name:1}) db.t1.f ...
- PL/SQL Developer 建立远程连接数据库的配置 和安装包+汉化包+注册机
PL/SQL Developer ,主要是讲一下如何配置PL/SQL Developer ,连接Oracle数据库. [知识点] 1.PL/SQL Developer 是什么? PL/SQL Deve ...
- Springboot整合mongodb时无法连接数据库
由于之前没有接触过mongodb,最近在学习时遇到了一些问题.用yml配置mongodb如下: spring: application: name:xc-service-manage-cms data ...
- Node.JS + MongoDB技术浅谈
看到一个Node.JS + MongoDB的小样例,分享给大家.魔乐科技软件学院(www.mldnjava.cn)的讲座 Node.JS + MongoDB技术讲座 云计算 +大数据 ...
- MFC+mongodb+nodejs 数据库的读取与写入操作
首先通过nodejs和mongodb建立后端服务器 一.在windows平台下启动mongodb服务器 1.进入mongodb的安装目录,并进去bin目录启动mongod 2.在d盘建立mongodb ...
随机推荐
- [dev][python] 从python2进阶到python3你都需要了解什么
基于python2快速掌握python3 0. 前言 这是一篇road map. 如果你会python2,读完这篇文章之后,你将掌握python3 1. 为什么会出现python3 Why Pytho ...
- Trivial File Transfer Protocol (TFTP)
Assignment 2The Trivial File Transfer Protocol (TFTP) is an Internet software utility fortransferrin ...
- Word图片、表格添加题注
1.首先为图片.表格添加题注: 2.通过交叉引用,如图**和图片.表的编号相关联起来:
- hdfs核心主件服务的启停方式
停止mapreduce服务 /hadoop/hadoop-2.6.4/sbin/stop-yarn.sh 启动mapreduce服务 /hadoop/hadoop-2.6.4/sbin/start-y ...
- vue-cli 创建项目失败
vue-cli 创建一个vue项目报错 npm code 404. 尝试解决方法都有,我是第3种方法生效 更新npm 重新安装nodejs vue-cli@3.0.1 在创建项目的时候,不能开启其他v ...
- opencart3属性attribute实现换行等简单html代码
opencart3属性attribute在前台页面默认是没有解析html代码功能的,比如想实现换行,后台这样写:line 1<br>line 2,但前台产品页也是line 1<br& ...
- 基于Servlet的MVC模式用户登录实例
关于MVC模式的简单解释 M Model,模型层,例如登录实例中,用于处理登录操作的类: V View,视图层,用于展示以及与用户交互.使用html.js.css.jsp.jQuery等前端技术实现: ...
- Oracle 12C执行root.sh CLSRSC-119 CRS-8503 CLSRSC-366
1.环境 OS:SUSE Linux Enterprise 12 SP3 X86_64 (Kernel: 4.4.162-94.69.2) DB:12.2.0.1 两节点RAC 参考文档:在 SLES ...
- python类与对象-如何派生内置不可变类型并修其改实例化行为
如何派生内置不可变类型并修其改实例化行为 问题举例 自定义一种新类型的元组,对传入的可迭代对象,我们只保留 其中int类型且值大于0的元素,例如 IntTuple([1, -1, 'abc', 6, ...
- Respone弹窗
Response.Write("<script>window.open('default.aspx?iID=" + GridView1.DataKeys[GridVie ...