前言
之前配置過Mongodb及Mongoose,但時(shí)間過于久遠(yuǎn),還是在此記錄下創(chuàng)建的過程。
首先要注意到的是Mongoose是對Mongodb的封裝,通過引入Schema方便進(jìn)行快速開發(fā)。
數(shù)據(jù)庫無需提前申請創(chuàng)建,mongoose是在創(chuàng)建了新實(shí)例后,調(diào)用save方法是發(fā)現(xiàn)沒有數(shù)據(jù)庫就會(huì)自動(dòng)創(chuàng)建。
通常將以下代碼放入mongodb_file.js文件中,導(dǎo)出實(shí)例的構(gòu)造函數(shù)。
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('數(shù)據(jù)庫連接成功');
});
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);
然后在需要的地方導(dǎo)入該模塊,使用構(gòu)造函數(shù)創(chuàng)建新的實(shí)例,保存即可
關(guān)于原生mongodb連接后的增刪改查的封裝,可以參考這篇文章