2017-07-26 22:03:18 +08:00
|
|
|
import mongoose from 'mongoose';
|
|
|
|
import yapi from '../yapi.js';
|
|
|
|
import autoIncrement from '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-07-27 15:06:42 +08:00
|
|
|
function connect() {
|
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:05:22 +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:05:22 +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-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-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
|
|
|
};
|