Skip to content

Instantly share code, notes, and snippets.

@tkh44
Last active February 19, 2022 22:06
Show Gist options
  • Save tkh44/f50c4841e939a5835d55 to your computer and use it in GitHub Desktop.
Save tkh44/f50c4841e939a5835d55 to your computer and use it in GitHub Desktop.
Generate users using randomuser.me and insert them into mongodb
var unirest = require('unirest');
var mongoose = require('mongoose');
var User = require('../models/User');
var async = require('async');
var secrets = require('../config/secrets');
mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
console.error('MongoDB Connection Error. Make sure MongoDB is running.');
});
unirest.get('http://api.randomuser.me/?results=40').end(function(response) {
var users = response.body.results;
async.each(users, function(obj, cb) {
var user = obj.user;
// Format the randomuser.me model to our models format
var newUser = new User({
email: user.email,
password: user.password,
profile: {
name: user.name,
gender: user.gender,
location: user.location,
picture: user.picture
}
});
console.log(newUser, '\n\n');
User.findOne({email: user.email}, function(err, existingUser) {
if (!existingUser) {
newUser.save(function(err) {
return cb(err ? err : null);
});
}
});
}, function(err) {
console.log(err ? err : '\n\n==========SUCCESS==========')
process.exit();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment