Skip to content

Instantly share code, notes, and snippets.

@lateau
Last active February 26, 2022 10:54
Show Gist options
  • Save lateau/e4eb67b373b8d8fa5d04ca35578031f2 to your computer and use it in GitHub Desktop.
Save lateau/e4eb67b373b8d8fa5d04ca35578031f2 to your computer and use it in GitHub Desktop.
kriasoft/react-starter-kit with mongoosejs
// src/data/models/index.js
import mongo from '../mongo';
import User from './User';
import UserLogin from './UserLogin';
import UserClaim from './UserClaim';
import UserProfile from './UserProfile';
async function sync() {
await mongo.disconnect();
const db = await mongo.connect();
const registeredModels = db.modelNames().slice();
registeredModels.forEach(modelName => delete db.models[modelName]);
// Load models here
db.model('User', User);
db.model('UserLogin', UserLogin);
db.model('UserClaim', UserClaim);
db.model('UserProfile', UserProfile);
}
function Model(name) {
return mongo.db.models[name];
}
export default { sync };
export { Model };
// src/data/mongo.js
import Bluebird from 'bluebird';
import mongoose from 'mongoose';
import config from '../config';
mongoose.Promise = Bluebird;
const mongo = {
db: null,
options: {
useMongoClient: true,
autoIndex: false,
},
async connect() {
this.db = await mongoose.connect(config.databaseUrl, this.options);
this.db.on('error', console.error.bind(console, 'connection error:'));
return this.db;
},
disconnect() {
return mongoose.disconnect();
},
};
export default mongo;
// src/server.js
//
// Launch the server
// -----------------------------------------------------------------------------
const promise = models.sync().catch(err => console.error(err.stack));
if (!module.hot) {
promise.then(() => {
app.listen(config.port, () => {
console.info(`The server is running at http://localhost:${config.port}/`);
});
});
}
//
// Hot Module Replacement
// -----------------------------------------------------------------------------
if (module.hot) {
app.hot = module.hot;
module.hot.accept('./router');
}
export default app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment