如何使用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 ...
随机推荐
- jsplumb 使用总结
1 删除连线问题 funcion clearDrawGraph { if (this.graphInstance !== null) { const connections = this.graphI ...
- 多线程之Executors基本使用
Executors几种创建方式 https://www.cnblogs.com/yasong/p/9318522.html 线程池数如何设置 https://blog.csdn.net/u013276 ...
- 用node在本机搭建一个极其简单的服务器
首先安装node, 建一个文件夹server, 在里面创建一个server.js,内容如下: var http = require("http"); http.createServ ...
- 常用数据类型的方法--str、int、list、dict
一.字符串类型(str) class str(basestring): """ str(object='') -> string Return a nice str ...
- spring-boot logback配置
接着上篇的代码,日志在不同环境下的配置也不一样,所以要分开配置,主要使用maven的profile 1.1 在pom.xml中添加 <profiles> <profile> & ...
- jackson 流式API
http://www.cnblogs.com/lee0oo0/articles/2652528.html Jackson提供了三种可选的JSON处理方法 1.流式API com.fasterx ...
- python之进程,线程,协程简单理解
进程:资源单位,由操作系统控制调度.正在执行的一个程序或者过程,进程之间不共享资源,进程间通讯手段:管道,队列,信号量等.多用于计算密集型场景,如金融计算 线程:是cpu的最小执行单位,由操作系统控制 ...
- leetcode143. Reorder List
用快慢双指针,可以使慢指针到达中间的时候快指针到达最后一个元素(奇数),或者倒数第二个元素(偶数).慢指针后面的元素是后半个链表,把后半个链表进行reverse,然后再插在原来的链表中就可以了 /** ...
- js左右大小变化
点左边左边变大.点右边右边大左边小 <style type="text/css"> *{ margin:0px auto; padding:0px; } #wai{ w ...
- 旧调重弹Hibernate与Ibatis区别——深入架构设计
对于一个粗学者而言一言概况就是:ibatis非常简单易学,hibernate相对较复杂,门槛较高. 但是,hibernate对数据库结构提供了较为完整的封装,hibernate的o/r mappin ...