There's more...

Now that our API is fully functional with MongoDB, it's very easy to create documents and have them available between application restarts. However, sometimes when working with an application, it's more desirable to make sure the data reverts to a consistent state so that development changes and experimentation don't result in unexpected database states.

One solution to this problem is to generate mock data, and to allow the application to reset its state to this mock data state upon start up. We can use the fabulous library faker.js to help us create some mock post records in our application:

npm install faker --save

All we need to do is use our NODE_ENV process variable as a flag for managing this behavior. We will make a simple mock generator method that will purge our database of stored records and generate a defined number of mock models for it. This way, upon restart, our database will be in a reliable state for any testing or functionality we need:

var Post = require('./models/posts');
var env = process.env.NODE_ENV || 'development';

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost/mean-db');

var generateMock = function(model, count, generateFake) {
console.log("purging all " + model.modelName + "...");
model.deleteMany({}, function() {

let mocks = [];
for (var i=0; i < count; i++) {

mocks.push(generateFake());
}


model.insertMany(mocks, function (error) {
if (error) return console.error('Failed to create mock ' + model.modelName);
console.log(count + " mock " + model.modelName + " created");
});
});
}
;

var mongo = mongoose.connection;
var db = mongo.db;
mongo.on('error', console.error.bind(console, 'failed to connect to mongodb:'));
mongo.once('open', function() {
if (env == 'development') {
var faker = require('faker');
generateMock(Post, 30, function() {

return {
title: faker.lorem.words(),
content: faker.lorem.sentences(),
published: faker.date.past()

}
});
}

});

module.exports = db;

Faker allows us to create randomly generated content for our posts that, while distinct from each other, is still the same type of content from post to post. This makes it much easier to have a reliable psuedo-realistic dataset in our database while still keeping things very consistent after each application restart.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.101.192