Example Seeds Pattern for Mongodb/Mongoose
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} ;
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 ) ,
] )
} )