Bit Hacker Logo
Bit Hacker Logo
Seeding MongoDB with Mongoose and Node.js

Seeding MongoDB with Mongoose and Node.js

In my last project I needed a way to seed a database with default values. I've seen a lot of findOneOrCreate() examples that attach an entirely new method to the schema. This is entirely unnecessary, instead we can use the findOneAndUpdate() method with the upsert parameter to insert a new document.

findOneAndUpdate()

The findOneAndUpdate() will find the first document that matches a filter, apply an the update and return the document. To make our seeding work, we supply the upsert property to create the document if it is not found.

findOneAndUpdate(filter, document, {
  upsert: true // Make this update into an upsert
})

seedDb

To put it together, we can create an array of our seed data then map over it to create our entries. We supply the filter and document as the same variable when using findOneAndUpdate().

const Category = require('../models/category')

function seedDB() {
    console.log('Seeding db...')

    let categories = [
        { name: 'Software Development' }
    ].map(async c => {
        return await Category.findOneAndUpdate(c,c,{upsert: true})
    })
}

There you have it! A very simple way to seed your database.