1.开启MongoDB服务
在命令行输入 net start mongodb 即可开启MongoDB服务。
2.创建数据库
在MongoDB中不需要显式创建数据库,如果正在使用的数据库不存在,MongoDB会自动帮我们创建数据库。
3.创建集合
创建集合实际上就是对集合设定规则。
// 设置集合规则
const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [ String ],
data: { type: Date, default: Date.now },
isPublished: Boolean
});
// 使用规则创建集合 返回集合类(集合构造函数)
const Course = mongoose.model('Course', courseSchema);
4.创建文档
创建文档实际上就是向集合插入具体的数据。
// 创建集合类的实例
const course = new Course({
name: 'Node.js course',
author: 'wangjian',
tags: ['node', 'backend'],
isPublished: true
});
// 保存实例
course.save();
插入数据的另一种形式
Course.create({name: 'JavaScript基础', author: '犀牛', isPublish: true}, (err, doc) => {
// 错误对象
console.log(err)
// 当前插入的文档
console.log(doc)
});
// create还支持promise 可以写成下面的形式
Course.create({name: 'JavaScript基础', author: '犀牛', isPublish: true})
.then(doc => console.log(doc))
.catch(err => console.log(err))
查询文档
Course.find({
name: 'wangjian',
isPublished: true
})
.limit(10),
.sort({name: 1}) // 1 升序 -1 降序
.select({name: 1, tags: 1})
.exec((err, data) => {})
删除文档
// 删除单个
Course.findOneAndDelete({}).then(result => console.log(result))
// findOneAndDelete只会删除一个如果有多条数据 就删除第一个
// 删除多个
User.deleteMany({}).then(result => console.log(result))
Course.findByIdAndRemove(id, err => {});
更新文档
// 更新单个
User.updateOne({查询条件}, {要修改的值}).then(result => console.log(result))
// 更新多个
User.updateMany({查询条件}, {要更改的值}).then(result => console.log(result))
// 根据id更新
Course.findByIdAndUpdate(id, {
$set: {
author: 'mosh',
isPublished: false
}
}, err => {})
终极大Boss
//查找数据
//查找集合user中所有的数据
user.find().then(result => console.log(result))
//查找集合user中id值为5d74ffec8da1c336180c9dbe的数据
user.find({ _id: '5d74ffec8da1c336180c9dbe' }).then(result => console.log(result))
//查找user集合中的第一条数据
user.findOne().then(result => console.log(result))
//查找user集合中属性‘name’的属性值为‘好啊好啊’的数据
user.findOne({ name: '好啊好啊' }).then(result => console.log(result))
//查询数据中年龄大于20,小于40的数据
user.find({ age: { $gt: 20, $lt: 40 } }).then(result => console.log(result))
//查找数据中爱好包括aaa的数据
user.find({ hobbies: { $in: ['aaa'] } }).then(result => console.log(result))
//查找整个数据中的name和email数据
user.find().select('name', 'email').then(result => console.log(result))
// 查找整个数据中的name和email数据,-号表示把数据前面的id去掉
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))
//查找数据,略过数据中的前两条,每次只显示两条,主要用于在分页的时候显示
user.find().skip(2).limit(2).then(result => console.log(result))
//删除数据
//在数据中查找出满足条件的一条数据,并且删除,返回的是一个promise对象
user.findOneAndDelete({ id: '5d74ffec8da1c336180c9dbe' }).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: 默认值
-
在catch中获取错误信息
Post.create({title:'aa', age: 60, category: 'java', author: 'bd'})
.then(result => console.log(result))
.catch(error => {
// 获取错误信息对象
const err = error.errors;
// 循环错误信息对象
for (var attr in err) {
// 将错误信息打印到控制台中
console.log(err[attr]['message']);
}
})