Mongoose第三方包:
使用Node.js操作MongoDB数据库需要依赖Node.js第三方包mongoose
使用npm install mongoose
命令下载
启动MongoDB
在命令行工具中运行net start mongoDB即可启动MongoDB,否则MongoDB将无法连接。
数据库连接:
使用mongoose提供的connect方法即可连接数据库
// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', {
useNewUrlParser: true,
useUnifiedTopology: true //这个即是报的警告
})
// 连接成功
.then(() => console.log('数据库连接成功'))
// 连接失败
.catch(err => console.log(err, '数据库连接失败'));
创建集合与文档:
创建集合分为两步,一是对对集合设定规则,二是创建集合,创建mongoose.Schema构造函数的实例即可创建集合。
创建文档实际上就是向集合中插入数据。
分为两步:
1.创建集合实例。
2.调用实例对象下的save方法将数据保存到数据库中。
// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true,useUnifiedTopology: true})
// 连接成功
.then(() => console.log('数据库连接成功'))
// 连接失败
.catch(err => console.log(err, '数据库连接失败'));
// 创建集合规则
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublished: Boolean
});
// 使用规则创建集合
// 1.集合名称
// 2.集合规则
const Course = mongoose.model('Course', courseSchema) // courses
// 创建文档
const course = new Course({
name: '数据可视化',
author: '你管我是谁',
isPublished: true
});
// 将文档插入到数据库中
course.save();
向集合中插入文档的另一种方式
// 向集合中插入文档
Course.create({name: 'Javascript', author: '啊啊啊', isPublished: false}, (err, result) => {
console.log(err)
console.log(result)
})
// 方式2
Course.create({name: 'Javascript123', author: 'aa', isPublished: false})
.then(result => {
console.log(result)
})
mongoDB数据库导入数据:
mongoimport -d playground -c users --file user.json
根据条件查询文档
//查询用户集合中的所有文档
User.find().then(result => console.log(result));
//通过_id字段查找文档
User.find({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result))
//findOne方法返回一条文档 默认返回当前集合中的第一条文档
User.findOne({name: '李四'}).then(result => console.log(result))
//查询用户集合中年龄字段大于20并且小于40的文档
User.find({age: {$gt: 20, $lt: 40}}).then(result => console.log(result))
//查询用户集合中hobbies字段值包含足球的文档 $in
User.find({hobbies: {$in: ['足球']}}).then(result => console.log(result))
//选择要查询的字段
User.find().select('name email -_id').then(result => console.log(result))
//根据年龄字段进行升序排列
User.find().sort('age').then(result => console.log(result))
//根据年龄字段进行降序排列
User.find().sort('-age').then(result => console.log(result))
//查询文档跳过前两条结果 限制显示3条结果
User.find().skip(2).limit(3).then(result => console.log(result))
删除文档:
// 查找到一条文档并且删除
// 返回删除的文档
// 如何查询条件匹配了多个文档 那么将会删除第一个匹配的文档
User.findOneAndDelete({_id: '5c09f267aeb04b22f8460968'}).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 数值最小为2
max: 100 数值最大为100
enum: ['html', 'css', 'javascript', 'node.js']
trim: true 去除字符串两边的空格
validate: 自定义验证器
default: 默认值 - 获取错误信息:error.errors['字段名称'].message
集合关联实现
通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。
- 使用id对集合进行关联
-
使用populate方法进行关联集合查询
image.png
// 用户集合
const User = mongoose.model('User', new mongoose.Schema({ name: { type: String } }));
// 文章集合
const Post = mongoose.model('Post', new mongoose.Schema({
title: { type: String },
// 使用ID将文章集合和作者集合进行关联
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}));
//联合查询
Post.find()
.populate('author')
.then((err, result) => console.log(result));