Skip to content

Instantly share code, notes, and snippets.

@jim-clark
Created August 7, 2017 20:41
Show Gist options
  • Save jim-clark/0199e64dd428dd00b7729c9eb0982f77 to your computer and use it in GitHub Desktop.
Save jim-clark/0199e64dd428dd00b7729c9eb0982f77 to your computer and use it in GitHub Desktop.
Seed DB with Mongoose
require('./database');
var Celebrity = require('../models/celebrity');
var Movie = require('../models/movie');
Promise.all([Celebrity.remove({}), Movie.remove({})])
.then(function() {
return Celebrity.create([
{name: 'Don Johnson'},
{name: 'Harrison Ford'},
{name: 'Chewy'},
{name: 'Val Kilmer'}
]);
})
.then(function(celebs) {
console.log('celebs created:\n', celebs);
return Movie.create([
{title: 'Star Wars', celebrities: [celebs[2]._id, celebs[1]._id]},
{title: 'Top Gun', celebrities: [celebs[3]._id]},
{title: 'Miami Vice - The Movie', celebrities: [celebs[0]._id]},
{title: 'Scarface'}
]);
})
.then(function(movies) {
// log out movies before populating celebrities
console.log('movies without populated celebrities:\n', movies);
// demo population of celebities
return Movie.find({}).populate('celebrities').exec();
})
.then(function(movies) {
// third arg in stringify specifies whitespace for pretty print
console.log('movies with populated celebrities:\n', JSON.stringify(movies, null, 2));
// remove Harrison Ford
return Celebrity.findOne({name: 'Harrison Ford'});
})
.then(function(harrison) {
return harrison.remove();
})
.then(function() {
// check if Harrison is removed
return Celebrity.find({});
})
.then(function(celebrities) {
// verify no more Harrison
console.log('verify no more Harrison:\n', celebrities);
// now gonna check post remove middleware on Celebrity model
return Movie.find({});
})
.then(function(movies) {
// verify Harrison removed from Star Wars
console.log('verify Harrison removed from Star Wars:\n', JSON.stringify(movies, null, 2));
})
.then(function() {
require('mongoose').connection.close();
process.exit();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment