安装
npm install mongoose
连接数据库
const mongoose = require('mongoose') mongoose.connect('mongodb://localhost:27017/test') // 连接数据库 // 数据库连接失败和成功函数 const db = mongoose.connection db.on('error', error => console.error(error)) db.on('open', () => console.log('数据库连接成功'))
插入数据
db.on('open', () => { // 定义数据模型 const KittenSchema = new mongoose.Schema({ name: String }) // 将schema转化为model const Kitten = mongoose.model('Kitten', KittenSchema) const kitten = new Kitten({ name:'喵喵喵' }) kitten.save().then(() => { console.log('数据存储成功') }) })
把数据库连接代码改造成Promise
const mongoose = require('mongoose') const dbs = 'mongodb://localhost:27017/test' exports.connect = () => { let maxConnectTimes = 0 return new Promise((resolve, reject) => { mongoose.connect(dbs) // 连接数据库 // 数据库连接失败和成功函数 const db = mongoose.connection db.on('disconnected', () => { maxConnectTimes++ if (maxConnectTimes < 5) { mongoose.connect(dbs) // 重新连接数据库 } else { reject('数据库挂了') } }) db.on('error', err => { if (maxConnectTimes >= 5) { reject(err) } }) db.on('open', () => { resolve() console.log('数据库连接成功') }) }) }