Skip to content

Instantly share code, notes, and snippets.

@chaiwa-berian
Last active October 23, 2019 12:50
Show Gist options
  • Save chaiwa-berian/996c632a1342061553cb4916c8966cc1 to your computer and use it in GitHub Desktop.
Save chaiwa-berian/996c632a1342061553cb4916c8966cc1 to your computer and use it in GitHub Desktop.
Initializing tables with default records via nodejs and mongoose
//refs to models
let User = require('../../app/common/models/user_models/user_model');
let UserRolePermission = require('../../app/common/models/user_models/user_role_permission_model');
let UserRole = require('../../app/common/models/user_models/user_role_model');
//=========================work starts here==================
let users_initialized;
let permissions_initialized;
let roles_initialized;
async function usersInitialized() {
let user_count = await User.estimatedDocumentCount({});
return (user_count > 0 );
}
async function permissionsInitialized() {
let permission_count = await UserRolePermission.estimatedDocumentCount({});
return (permission_count > 0);
}
async function rolesInitialized() {
let role_count = await UserRole.estimatedDocumentCount({});
return (role_count > 0);
}
async function dbInitialized() {
[users_initialized, permissions_initialized, roles_initialized] = await Promise.all([usersInitialized(), permissionsInitialized(), rolesInitialized()]);
console.log('users_initialized:' + users_initialized);
console.log('permissions_initialized:' + permissions_initialized);
console.log('roles_initialized:' + roles_initialized);
return (users_initialized && await permissions_initialized && await roles_initialized);
}
async function initializeDb() {
//Never mind definitions for these bootstrap functions
await bootStrapPermissions();
await bootStrapRoles();
await bootStrapUsers();
}
module.exports = {
dbInitialized,
initializeDb
}
const dbInitialized = require('../helpers/db/db_initialization').dbInitialized;
const initializeDb = require('../helpers/db/db_initialization').initializeDb;
const mongoose = require('mongoose');
//skipped a few more declarations here
var db_connection = mongoose.connection;
//Every time I connect to db, I want to check if db key tables have been initialized else I initialize them with some default records
db_connection.on('connected', async function () {
console.log('connected to the database server!');
let db_boot_strap_done = await dbInitialized();
if (db_boot_strap_done === false) {
console.log('[' + app_name + '] ' + 'Attempting to initialize collections in the database...');
await initializeDb();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment