Skip to content

Instantly share code, notes, and snippets.

@justsml
Last active January 15, 2020 22:17
Show Gist options
  • Save justsml/c67fddfd9187c30da1d955050b30450a to your computer and use it in GitHub Desktop.
Save justsml/c67fddfd9187c30da1d955050b30450a to your computer and use it in GitHub Desktop.
Uses mongoose

Example Seeds Pattern for Mongodb/Mongoose

Example Schemas:

models.js
const mongoose = require('mongoose');

// Category Schema
const categorySchema = mongoose.Schema({
  name: {type: String, unique: true},
});

// Article schema, refers to categories
const articleSchema = mongoose.Schema({
  category: { ref: 'Category', type: mongoose.Schema.Types.ObjectId },
  title: String
});

const article = mongoose.model('Article', articleSchema);
const category = mongoose.model('Category', categorySchema);

module.exports = {article, category};

Example seeds.js

const mongoose = require('mongoose');
const ObjectId = mongoose.ObjectId;
const Category = mongoose.model('Category');
const Article  = mongoose.model('Article');

const techId = ObjectId()

const data = {
  categories: [{_id: techId, name: 'Tech'}]
  articles: [{title: 'Blah blah bitcoin', category: techId}]
}

Promise.all([
// Step #1, delete ALL from each collection
  Category.remove({}),
  Article.remove({}),
])
.then(() => {
  return Promise.all([
    Category.insert(data.categories),
    Article.insert(data.articles),
  ])
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment