So, I\'m new to the MEAN stack, and I\'ve hit a wall trying to seed MongoDB. I\'m using Mongoose to communicate with the database, and there\'s a bunch of documentation suggesti
I solved this issue on a project by dumping the relevant data to an extended JSON array formatted file using mongoexport --jsonArray
, then importing this back into POJO format inside the Node application using the EJSON
package. I then just use Mongoose to insert the resulting JS array back into the database using the correct collection model you've created using Mongoose.
The necessary JSON data files to seed the application for a first-run are checked into the application repository. Here's a quick sample you may be able to adapt to your purposes:
// ...
// 'Items' is the Mongoose collection model.
const itemResult = await Items.find({}).exec();
if(itemResult.length === 0) {
const itemsSeedDataRaw = fs.readFileSync(`${__dirname}/data/items.json`, 'utf8');
const itemsSeedData = EJSON.parse(itemsSeedDataRaw);
await Items.insertMany(itemsSeedData);
}
// ...