前言
之前配置过Mongodb及Mongoose,但时间过于久远,还是在此记录下创建的过程。
首先要注意到的是Mongoose是对Mongodb的封装,通过引入Schema方便进行快速开发。
数据库无需提前申请创建,mongoose是在创建了新实例后,调用save方法是发现没有数据库就会自动创建。
通常将以下代码放入mongodb_file.js文件中,导出实例的构造函数。
let mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/weather', {useNewUrlParser: true});
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.on('open', () => {
console.log('数据库连接成功');
});
let Schema = mongoose.Schema;
let Weather = new Schema({
time: String,
temperature: String,
rainfall: String,
windspeed: String,
winddirection: String,
airpressure: String,
humidity: String,
});
module.exports = mongoose.model('Weather',Weather);
然后在需要的地方导入该模块,使用构造函数创建新的实例,保存即可
关于原生mongodb连接后的增删改查的封装,可以参考这篇文章