yapi/server/utils/db.js

48 lines
1.1 KiB
JavaScript
Raw Normal View History

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) {
schema = new mongoose.Schema(schema);
}
schema.set('autoIndex', false);
return yapi.connect.model(model, schema, model);
}
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;
let config = yapi.WEBCONFIG;
let options = {};
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;
options.pass = config.db.pass;
}
2017-08-15 12:08:59 +08:00
2017-07-27 15:06:42 +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 () {
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) {
yapi.commons.log(err, 'Mongo connect error');
});
2017-07-03 16:16:05 +08:00
autoIncrement.initialize(db);
2017-07-03 16:16:05 +08:00
return db;
}
yapi.db = model;
2017-08-23 16:11:43 +08:00
2017-07-27 15:06:42 +08:00
module.exports = {
model: model,
connect: connect
};