如何使用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 ...
随机推荐
- Android的SQlite的使用
Android系统集成了一个轻量级的数据库:SQlite.SQlite不像Oracle.MySQl数据库那样需要安装.启动服务器进程,SQLite数据库只是一个文件 实例1:向数据库里插入数据 主界面 ...
- 一对一关联模型,HAS_ONE
class UserModel extends RelationModel{ protected $_link = array( 'Profile'=> HAS_ONE, //就这一行就行了 ) ...
- CRT乱码问题
本人在使用CRT过程中遇到乱码问题,经调试发现要把字体调整为"新宋体",编码格式用"UTF-8". 调整字体: Options à Session option ...
- windows下安装Mongodb的方法
参考:https://blog.csdn.net/heshushun/article/details/77776706
- Hello greenDAO(SQLite)
一.配置Gradle Scripts: 1.1.build.gradle(Project:*****) buildscript { repositories { google() jcenter() ...
- 程序设计与算法(一)C语言程序设计CAP之字符串
C++中的字符串 字符串有三种形式 用双引号括起来的字符串常量,如果"CHINA"."C++ program" 存放于字符串数组中,以'\0'字符(ASCII吗 ...
- java实验一总结
实验一第一部分 在Linux中运行结果 通过cd和mkdir命令建立tree,带包编译并用 javac -d bin 的命令将编译文件保存在bin目录中 通过 java -cp 的命令运行带包的程序 ...
- Anaconda spyder 设置tab键为2个空格
tool -> Preference->
- POJ 3162 bit区间查询最值+树形DP
POJ 3162 『题目链接』POJ 3162 『题目类型』bit区间查询最值+树形DP ✡Problem: 一棵n个节点的树.wc爱跑步,跑n天,第i天从第i个节点开始跑步,每次跑到距第i个节点最远 ...
- C# 使用Newtonsoft.Json读写Json文件
{ "CAN": false, "AccCode": 4294901856, "Id": 768, "BPointMove&quo ...