基于项目开发的 MonggoDB 基本使用命令
1.关于 MonggoDB 的简单介绍
MongoDB 是由 C++语言编写的,是一个基于分布式文件存储的开源数据库系统,旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。
- 中文手册
- 官网
- 可视(图形)化管理工具下载地址
【注意】在 MongoDB 版本中,是偶数:如 3.2.x、3.4.x、3.6.x 表示正式版(可用于生产环境),奇数:3.1.x、3.3.x、3.5.x 表示开发版。根据自己情况选择。
2.数据库连接
mongodb 的默认端口为 27017,连接时后面接数据库名称,{ useNewUrlParser: true, useCreateIndex: true}
在控制台过滤冗余信息。
1 2 3 4 5 6 7 8 9 10
| const mongoose = require('mongoose')
mongoose .connect('mongodb://localhost:27017/myweb', { useNewUrlParser: true, useCreateIndex: true, }) .then(() => console.log('数据库连接成功')) .catch(() => console.log('数据库连接失败'))
|
创建其他集合,无非三步:
- 导入 monggodb 模版
- 创建集合规则
- 创建集合,并导出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| const mongoose = require('mongoose') const userSchema = new mongoose.Schema({ username: { type: String, required: true, minlength: 2, maxlength: 20, }, email: { type: String, unique: true, required: true, }, password: { type: String, required: true, }, role: { type: String, required: true, }, })
const User = mongoose.model('User', userSchema)
module.exports = { User, }
|
1 2 3 4 5 6 7 8 9 10 11 12
|
async function createUser() { const salt = await bcrypt.genSalt(10) const pass = await bcrypt.hash('11', salt) const user = await User.create({ username: 'nanmo', email: 'qq@qq.com', password: pass, role: 'admin', }) }
|

某个 blog 项目用户集合,处于安全性考虑,将用户密吗通过bcrypt.hash
加密处理。
3.基本数据库命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| db.userl.find().help(); show dbs use student show collections db.version();
db.集合名.insert({name:"",age:xx}) db.user.insert({"name":"suyl","sex":"男",age:32});
db.集合名.remove(条件[,是否删除一条]) db.users.remove({age: 132}); db.user.remove({}) db.dropDatabase()
db.集合名.find({查询条件},{查询列}) db.user.find({"sex":"男"}); db.user.find({age:{$gt:10}})
db.user.find({"name":/su/}); db.user.find().limit(2) db.user.find().skip(1)
db.集合名.update(条件,新数据[,是否新增,是否修改多条]) db.user.update({"name":"张三"},{"name":"李四","sex":"男",age:32})
db.user.find({}).sort({"age":1}) db.user.find({}).sort({"age":-1}) db.student.getIndexes() db.student.dropIndex({"name":1})
|
到此,完毕