Video Course

Create a CRUD App with Node and MongoDB: Lesson 9 of 17

Seeding Database

Up Next

MongoDB GUI: Robomongo

Autoplaying in 7 seconds!

Cancel

To seed the database, we'll pull the events we used earlier. We'll loop over them using an ES6 for...of loop.

Grab the events and loop over them to save using mongoose.

/**
 * Seed the database
 */
function seedEvents(req, res) {
  // create some events
  const events = [
    { name: 'Basketball', description: 'Throwing into a basket.' },
    { name: 'Swimming', description: 'Michael Phelps is the fast fish.' },
    { name: 'Weightlifting', description: 'Lifting heavy things up' },
    { name: 'Ping Pong', description: 'Super fast paddles' }
  ];

  // use the Event model to insert/save
  for (event of events) {
    var newEvent = new Event(event);
    newEvent.save();
  }

  // seeded!
  res.send('Database seeded!');
}

Chris Sevilleja

162 posts

Co-founder of Scotch.io. Slapping the keyboard until something good happens.