MongoDBNode.jsTutorial

Seed MongoDB with mongoose-seed

Give your database a useful starting state. A short, practical guide to seeding MongoDB during development, from 2019.

Temitayo Adeeyo2 min read

From the archive

An early tutorial from my first years of writing in public, preserved as part of the record. The engineer who wrote it was still learning out loud. Some practices here are not how I would build today, and that's rather the point.

First, what is database seeding?1

Seeding a database is the process of providing an initial set of data to a database when it's being set up. It's especially useful during development, when you want the database populated with realistic data to build against instead of starting from an empty screen every time.

Now that we know what seeding is, let's write some code. I'll assume you're familiar with Node.js and MongoDB, and that you have a Node server set up.

The product model

Create a product.model.js file.

product.model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
 
const productSchema = new Schema(
  {
    name: { type: String },
    price: { type: Number },
    description: { type: String },
    in_stock: { type: Boolean, default: true },
  },
  { timestamps: true }
);
 
const productModel = mongoose.model('product', productSchema, 'Products');
module.exports = productModel;

The controller and route

Create product.controller.js with a simple create handler.

product.controller.js
const ProductModel = require('./product.model');
 
exports.create = async (req, res, next) => {
  try {
    const product = new ProductModel(req.body);
    const saved = await product.save();
    return res.status(201).json({ status: true, data: saved });
  } catch (error) {
    return next(error);
  }
};
 
exports.find = async (req, res, next) => {
  try {
    const products = await ProductModel.find().sort({ createdAt: -1 });
    return res.status(200).json({ status: true, data: products });
  } catch (error) {
    return next(error);
  }
};

And here is a product.route.js to expose it.

product.route.js
const { Router } = require('express');
const ProductController = require('./product.controller');
 
const router = Router();
router.post('/product', ProductController.create);
router.get('/products', ProductController.find);
 
module.exports = router;

The seed file

Here's where mongoose-seed comes in. It loads your Mongoose models, optionally clears existing documents, and populates the collections from plain data objects. Create a seed.js file.

seed.js
const seeder = require('mongoose-seed');
const db = 'mongodb://localhost:27017/yourdatabase';
 
const data = [
  {
    model: 'product',
    documents: [
      { name: 'Ankara fabric', price: 4500, description: 'Six yards, premium wax print' },
      { name: 'Leather sandals', price: 7000, description: 'Handmade in Aba' },
      { name: 'Shea butter (1kg)', price: 3000, description: 'Unrefined, from Ghana' },
    ],
  },
];
 
seeder.connect(db, () => {
  // Load the model into the seeder
  seeder.loadModels(['./product.model.js']);
 
  // Clear existing documents, then populate // [!code highlight]
  seeder.clearModels(['product'], () => {
    seeder.populateModels(data, () => {
      seeder.disconnect();
    });
  });
});

Wire it into package.json

Add a seed script.

package.json
{
  "scripts": {
    "seed": "node seed.js"
  }
}

Now run it.

npm run seed

That's it, your MongoDB is seeded and your development environment starts with data worth developing against. To go deeper, read the mongoose-seed documentation.

Enjoy!

Footnotes

  1. Originally published on my Hashnode blog in October 2019, one day after my first tutorial. Revised for this site with the code in text instead of screenshots.