forked from busbud/coding-challenge-backend-c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
seed.js
48 lines (46 loc) · 1.17 KB
/
seed.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
'use strict';
/**
* seed.js
* ------------------------------
* Seeding TSV data through Mongoose's models
*/
const citiesDataFilePathTSV = './data/cities_canada-usa.tsv';
var _ = require('lodash'),
Promise = require('bluebird'),
fs = require('fs'),
parser = require('csv-parse/lib/sync'),
mongoose = require('mongoose'),
City = mongoose.model('CitySchema');
/**
* Synchronously seeds the database from TSV data
* @return {Promise}
*/
module.exports = function() {
return new Promise(function (resolve, reject) {
City.findAsync()
.then(results => {
if (results.length > 0) {
return resolve();
}
console.log('Reading input file...');
var data = fs.readFileSync(citiesDataFilePathTSV, "utf8")
console.log('File read.');
var records = parser(data, {columns: true, delimiter: '\t', quote: '$', auto_parse: true});
async.each(records, function(city, cb) {
City.create(
_.extend({
latLng : {
type: "Point",
coordinates: [city.long, city.lat]
}
}, city), function(err) {
if(err) console.log(err);
cb();
});
}, function(err){
if(err) reject(err);
resolve();
});
}).catch(reject);
});
};