Skip to content

Instantly share code, notes, and snippets.

@rttomlinson
Last active July 25, 2019 16:13
Show Gist options
  • Save rttomlinson/10c658ea276d3cfc1dc90b391af4c817 to your computer and use it in GitHub Desktop.
Save rttomlinson/10c658ea276d3cfc1dc90b391af4c817 to your computer and use it in GitHub Desktop.
Mongoose Initialization
{
"development": {
"database": "demo_exploring_mongoose_development",
"host": "localhost"
},
"test": {
"database": "demo_exploring_mongoose_test",
"host": "localhost"
},
"production": {
"use_env_variable": "MONGODB_URI"
}
}
var mongoose = require('mongoose');
var bluebird = require('bluebird');
// Set bluebird as the promise
// library for mongoose
mongoose.Promise = bluebird;
var models = {};
// Load models and attach to models here
models.User = require('./user');
//... more models
module.exports = models;
var mongoose = require('mongoose');
var env = process.env.NODE_ENV || 'development';
var config = require('./config/mongo')[env];
module.exports = () => {
var envUrl = process.env[config.use_env_variable];
var localUrl = `mongodb://${ config.host }/${ config.database }`;
var mongoUrl = envUrl ? envUrl : localUrl;
return mongoose.connect(mongoUrl);
};
// Require mongoose and start up the REPL
// Also require our models
var mongoose = require('mongoose');
var repl = require('repl').start({});
var models = require('./models');
// Use our promise based connection
// file to wrap our REPL and execute
// only once we've connected to MongoDB
require('./mongo')().then(() => {
// Set `models` to be available in
// the REPL by name
repl.context.models = models;
// Set each model to be available in the REPL
// by name
Object.keys(models).forEach((modelName) => {
repl.context[modelName] = mongoose.model(modelName);
});
// Helper function to output the result of
// a query
repl.context.lg = (data) => console.log(data);
});
var mongoose = require('mongoose');
module.exports = () => {
// Get all collections in db
var collections = mongoose
.connection
.collections;
// Get collection key names
var collectionKeys = Object.keys(collections);
// Store the promises from our
// remove() calls
var promises = [];
// Iterate over all collection
// removing each and storing the promise
collectionKeys.forEach((key) => {
var promise = collections[key].remove();
promises.push(promise);
});
// Return a single promise
// that resolves when
// all collections have been
// removed
return Promise.all(promises);
};
var mongoose = require('mongoose');
var models = require('./../models');
// Assign models to the global namespace
// so we can reference them easily
// in seeds/seeds.js
Object.keys(models).forEach((modelName) => {
global[modelName] = mongoose.model(modelName);
});
// Connect to MongoDB
require('./../mongo')()
// Clean the database
.then(() => console.log('Cleaning Database...'))
.then(() => {
return require('./clean')();
})
// Seed the data
.then(() => console.log('Seeding...'))
.then(() => {
return require('./seeds')();
})
// Success!
.then(() => console.log('Done'))
// Fail :(
.catch((e) => console.error(e))
// Always disconnect
.then(() => mongoose.disconnect());
var faker = require('faker');
var voca = require('voca');
const MULTIPLIER = 1;
function randomTitle(type) {
type = voca.titleCase(type);
var randomWord = faker.random.word();
randomWord = voca.titleCase(randomWord);
var names = [
`The ${ randomWord } Inn`,
`${ type } ${ randomWord }`,
`${ randomWord } ${ type }`
];
var index = Math.floor(Math.random() * names.length);
return names[index];
}
module.exports = () => {
// ----------------------------------------
// Create Users
// ----------------------------------------
console.log('Creating Users');
var users = [];
for (let i = 1; i < MULTIPLIER * 10; i++) {
var user = new User({
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.random.word(),
email: faker.internet.email()
});
users.push(user);
}
// ----------------------------------------
// Create Posts
// ----------------------------------------
console.log('Creating Posts');
var posts = [];
for (let i = 1; i < MULTIPLIER * 50; i++) {
var author = users[Math.floor(Math.random() * users.length)]
var post = new Post({
title: randomTitle('books'),
body: randomTitle('books'),
author: author._id,
});
posts.push(post);
}
// ----------------------------------------
// Create Comments
// ----------------------------------------
console.log('Creating Comments');
var comments = [];
for (let i = 1; i < MULTIPLIER * 50; i++) {
let author = users[Math.floor(Math.random() * users.length)];
let post = posts[Math.floor(Math.random() * posts.length)];
var comment = new Comment({
title: randomTitle('books'),
body: randomTitle('books'),
author: author._id,
parent: post._id
});
post.comments.push(comment);
comments.push(comment);
}
// ----------------------------------------
// Finish
// ----------------------------------------
console.log('Saving...');
var promises = [];
[
users,
posts,
comments
].forEach((collection) => {
collection.forEach((model) => {
promises.push(model.save());
});
});
return Promise.all(promises);
};
require('./mongo')().then(() => {
//... Start using the MongoDB connection
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment