什么是Moongoose
- Mongoose是一个文档对象模型库,它对Node原生的MongoDB模块进行了进一步的优化封装,并提供了更多的功能
优点
- 可以为文档创建一个模式结构Scheme
- 可以对模型中的对象/文档进行验证
- 数据可以通过类型转换转换为对象模型
- 可以使用中间件处理应用业务逻辑
- 比Node原生操作MongoDB更加简单、便捷
Mongoose的使用
连接数据库
const mongoose = require('mongoose')const DB_NAME = 'student';const DB_URL = 'localhost:27017'let dbPromise = new Promise((resolve, reject) => { mongoose.connect(`mongodb://${DB_URL}/${DB_NAME}`, {useNewUrlParser: true, useUnifiedTopology: true}) mongoose.connection.on('open', (err) => { if (!err) { console.log('数据库连接成功!'); resolve(); } else { reject(err) } });});
创建模型对象
const mongoose = require('mongoose')// 1.引入约束Schemalet Schema = mongoose.Schema;// 2.创建一个约束对象实例let studentSchema = new Schema({ stu_no: { type: String, required: true, unique: true }, name: { type: String, required: true }, age: { type: Number, required: true }, sex: { type: String, required: true }, hobby: { type: [String] }, info: { type: Schema.Types.Mixed // 接收任意类型 }, date: { type: Date, default: Date.now() }, enable_flag: { type: String, default: 'Y' }});// 3.创建模型对象let studentModel = mongoose.model('students', studentSchema);
使用模型对象操作数据库
增加
// 第一种写法dbPromise.then(() => { studentModel.create({ stu_no: '2019180001', name: '哈哈', age: 18, sex: '男', hobby: ['看书', '学习'], info: 'He is a good man' }, (err, data) => { if (!err) { console.log('数据写入成功', data) } else { console.log(err) } })}).catch((err) => { console.log(err)});// 第二种写法dbPromise.then(() => { studentModel.create({ stu_no: '2019180001', name: '哈哈', age: 18, sex: '男', hobby: ['看书', '学习'], info: 'He is a good man' }, (err, data) => { if (!err) { console.log('数据写入成功', data) } else { console.log(err) } })}, (err) => { console.log(err)})// 第三种写法(async () => { await dbPromise; studentModel.create({ stu_no: '2019180001', name: '哈哈', age: 18, sex: '男', hobby: ['看书', '学习'], info: 'He is a good man' }, (err, data) => { if (!err) { console.log('数据写入成功', data) } else { console.log(err) } })})()
删除
dbPromise.then(() => { studentModel.deleteOne({ // 或者deleteMany stu_no: '2019180001' }, (err, data) => { if (!err) { console.log(data) } else { console.log(err) } })}).catch((err) => { console.log(err)});
修改
dbPromise.then(() => { studentModel.updateOne({ // 或者upodateMany stu_no: '2019180001' },{age: 28}, (err, data) => { if (!err) { console.log(data) } else { console.log(err) } })}).catch((err) => { console.log(err)});
查询
dbPromise.then(() => { studentModel.find({ stu_no: '2019180001' }, (err, data) => { if (!err) { console.log(data) } else { console.log(err) } })}).catch((err) => { console.log(err)});