2017-09-03 08:43:13 +08:00
|
|
|
const mongoose = require('mongoose');
|
|
|
|
const yapi = require('../yapi.js');
|
|
|
|
const autoIncrement = require('mongoose-auto-increment');
|
2017-07-03 16:16:05 +08:00
|
|
|
|
2017-07-27 15:06:42 +08:00
|
|
|
function model(model, schema) {
|
|
|
|
if (schema instanceof mongoose.Schema === false) {
|
2017-07-05 16:17:58 +08:00
|
|
|
schema = new mongoose.Schema(schema);
|
|
|
|
}
|
2017-07-26 22:03:18 +08:00
|
|
|
|
2017-07-05 16:17:58 +08:00
|
|
|
schema.set('autoIndex', false);
|
2017-07-26 22:03:18 +08:00
|
|
|
|
|
|
|
return yapi.connect.model(model, schema, model);
|
2017-07-04 16:43:07 +08:00
|
|
|
}
|
2017-07-03 16:16:05 +08:00
|
|
|
|
2017-08-23 16:11:43 +08:00
|
|
|
function connect(callback) {
|
2017-07-03 16:16:05 +08:00
|
|
|
mongoose.Promise = global.Promise;
|
2017-07-26 22:03:18 +08:00
|
|
|
|
2017-07-04 16:43:07 +08:00
|
|
|
let config = yapi.WEBCONFIG;
|
2017-07-26 11:26:28 +08:00
|
|
|
let options = {};
|
2017-07-26 22:03:18 +08:00
|
|
|
|
2017-08-15 12:08:59 +08:00
|
|
|
if (config.db.user) {
|
2017-07-27 15:06:42 +08:00
|
|
|
options.user = config.db.user;
|
2017-07-26 22:03:18 +08:00
|
|
|
options.pass = config.db.pass;
|
2017-07-26 11:26:28 +08:00
|
|
|
}
|
2017-08-15 12:08:59 +08:00
|
|
|
|
2017-07-27 15:06:42 +08:00
|
|
|
|
2017-07-26 11:26:28 +08:00
|
|
|
let db = mongoose.connect(`mongodb://${config.db.servername}:${config.db.port}/${config.db.DATABASE}`, options);
|
2017-07-03 16:16:05 +08:00
|
|
|
|
2017-07-27 15:06:42 +08:00
|
|
|
db.then(function () {
|
2017-07-26 22:03:18 +08:00
|
|
|
yapi.commons.log('mongodb load success...');
|
2017-08-23 16:11:43 +08:00
|
|
|
if(typeof callback === 'function'){
|
|
|
|
callback.call(db)
|
|
|
|
}
|
2017-07-03 16:16:05 +08:00
|
|
|
}, function (err) {
|
2017-07-04 16:43:07 +08:00
|
|
|
yapi.commons.log(err, 'Mongo connect error');
|
2017-07-26 22:03:18 +08:00
|
|
|
});
|
2017-07-03 16:16:05 +08:00
|
|
|
|
2017-07-05 16:17:58 +08:00
|
|
|
autoIncrement.initialize(db);
|
2017-07-03 16:16:05 +08:00
|
|
|
return db;
|
|
|
|
}
|
|
|
|
|
2017-07-04 16:43:07 +08:00
|
|
|
yapi.db = model;
|
|
|
|
|
2017-08-23 16:11:43 +08:00
|
|
|
|
2017-07-27 15:06:42 +08:00
|
|
|
module.exports = {
|
2017-07-04 16:43:07 +08:00
|
|
|
model: model,
|
|
|
|
connect: connect
|
2017-07-26 22:03:18 +08:00
|
|
|
};
|