mongoose的使用方法就不谈了,主要说说nodejs封装的过程
1.首先是schema对象
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
/*
*schema对象,将模型暴漏出去
* */
let collection = {
fishtimes:{
total:{
type:Number
},
today:{
type:Number
}
};
}
module.exports = {
collections : collection,
fishtimes:mongoose.model('fishtimes',collection['fishtimes'])
};
因为mongoose一个特点,模型一旦实例化后不能重写,所以要将实例化好的暴漏出去
2.接着是实现封装过程,单例模式
const mongo = require('mongoose'),
path = require('path'),
schema = require(path.join(__dirname, '/schema')),
collections = schema.collections;
let dbName,
url = 'mongodb://localhost:27017/';
mongo.set('useCreateIndex', true);
class Mongo {
static getInstance(db) {
dbName = db || 'fishlog';
if (!this.instance) {
this.instance = new Mongo();
}
return this.instance;
}
constructor() {
if (