使用 Node.js 操作 MongoDB 数据库需要依赖 Node.js 第三方包 mongoose
使用 npm install mongoose 命令下载
连接数据库
使用mongoose提供的 connect 方法即可连接数据库
// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
// 连接成功
.then(() => console.log('数据库连接成功'))
// 连接失败
.catch(err => console.log(err, '数据库连接失败'));
创建集合
创建集合分为两步,一是对对集合设定规则,二是创建集合,创建 mongoose.Schema 构造函数的实例即可创建集合
//创建集合规则
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublished: Boolean
});
//使用规则创建集合构造函数
const Course = mongoose.model('Course', courseSchema);
创建文档(插入数据)
创建文档实际上就是向集合中插入数据。
第一种方法:
- 创建集合实例
- 调用实例对象下的 save 方法将数据保存到数据库中
//1、插入文档的第一种方法
//创建实例文档
const course = new Course({
name: 'node.js',
author: 'Jinle',
isPublished: true
});
// 返回一个实例对象
//将文档插入到数据库中
course.save();
第二种方法:
//2、插入文档的另一种方法
Course.create({ name: 'JavaScript基础', author: 'Jinle', isPublished: false }, (err, doc) => {
// 错误对象
console.log(err)
// 当前插入的文档
console.log(doc)
});
//create方法也是返回promise对象
Course.create({ name: 'HTML', author: 'Jinle', isPublished: true })
.then((result) => {
console.log(result);
})
导入数据
mongoimport –d 数据库名称 –c 集合名称 –file 要导入的数据文件
查询文档(数据)
- find() 默认查询用户集合所有文档
User.find().then(result => console.log(result));
-
find('条件') 通过条件查找文档
User.find({ _id: '5c09f267aeb04b22f8460968' }).then(result => console.log(result));
-
findOne() 方法返回一条文档 默认返回当前集合中的第一条文档
User.findOne({name: '李四'}).then(result => console.log(result));
-
{属性: {$gt: 最小值, $lt: 最大值}} 匹配大于小于值
//查询用户集合中年龄字段大于20并且小于40的文档
User.find({ age: { $gt: 20, $lt: 40 } }).then(result => console.log(result));
-
{属性: {$in: [包含字符]}} 匹配包含字符
//查询用户集合中hobbies字段值包含足球的文档
User.find({ hobbies: { $in: ['足球'] } }).then(result => console.log(result));
-
select('属性') 选择要查询的字段,-属性 是不查询
User.find().select('name email -_id').then(result => console.log(result));
-
sort(' (-) 属性') 按照属性升降序排序
//根据年龄字段进行升序排列
User.find().sort('age').then(result => console.log(result));
//根据年龄字段进行降序排列
User.find().sort('-age').then(result => console.log(result));
- skip() 跳过多少条数据,limit() 限制查询数量
// 查询文档跳过前两条结果 限制显示3条结果
User.find().skip(2).limit(3).then(result => console.log(result));
删除文档(数据)
- 删除单个
查找到一条文档并且删除,返回删除的文档
如何查询条件匹配了多个文档 那么将会删除第一个匹配的文档
Course.findOneAndDelete({}).then(result => console.log(result))
- 删除多个
删除多条文档 空默认删除全部
User.deleteMany({}).then(result => console.log(result))
更新文档(数据)
- 更新单个
User.updateOne({查询条件}, {要修改的值}).then(result => console.log(result))
- 更新多个
User.updateMany({查询条件}, {要更改的值}).then(result => console.log(result))
mongoose验证
在创建集合规则时,可以设置当前字段的验证规则,验证失败就则输入插入失败。
required: true 必传字段minlength: 3 字符串最小长度maxlength : 20 字符串最大长度min: 2 数值最小为 2max: 100 数值最大为 100enum: ['html', 'css', 'javascript', 'node.js' ] 列举出当前字段可以拥有的值trim: true 去除字符串两边的空格validate: 自定义验证器default: 默认值
const postSchema = new mongoose.Schema({
title: {
type: String,
// 必选字段
required: [true, '请传入文章标题'],
// 字符串的最小长度
minlength: [2, '文章长度不能小于2'],
// 字符串的最大长度
maxlength: [5, '文章长度最大不能超过5'],
// 去除字符串两边的空格
trim: true
},
age: {
type: Number,
// 数字的最小范围
min: 18,
// 数字的最大范围
max: 100
},
publishDate: {
type: Date,
// 默认值
default: Date.now
},
category: {
type: String,
// 枚举 列举出当前字段可以拥有的值
enum: {
values: ['html', 'css', 'javascript', 'node.js'],
message: '分类名称要在一定的范围内才可以'
}
},
author: {
type: String,
validate: {
validator: v => {
// 返回布尔值
// true 验证成功
// false 验证失败
// v 要验证的值
return v && v.length > 4
},
// 自定义错误信息
message: '传入的值不符合验证规则'
}
}
});
集合关联实现
通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。
// 用户集合规则
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
// 文章集合规则
const postSchema = new mongoose.Schema({
title: {
type: String
},
// 使用ID将文章集合和作者集合进行关联
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
// 用户集合
const User = mongoose.model('User', userSchema);
// 文章集合
const Post = mongoose.model('Post', postSchema);
//联合查询
Post.find().populate('author').then(result => console.log(result))