-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimport.js
87 lines (69 loc) · 1.82 KB
/
import.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
process.title = 'node_csv_mongo_import'
const csv = require('csvtojson')
const fs = require('fs')
const _ = require('lodash')
const mongoose = require('mongoose')
const shortid = require('shortid')
const {MONGO_URI, CSV_FILE, MODEL_NAME} = process.env
const log = console.log
if (!MONGO_URI || !CSV_FILE || !MODEL_NAME) {
log(`
Usage:
MONGO_URI=mongodb://localhost/petdb CSV_FILE=mypets.csv MODEL_NAME=Pets node import.js
`)
process.exit(1)
}
const start = +new Date()
const Model = mongoose.model(MODEL_NAME, new mongoose.Schema({
_id: {
type: String,
default: () => `${MODEL_NAME.substring(0, 3).toLowerCase()}-${shortid()}`
}
}, { strict: false }))
log({ MONGO_URI, CSV_FILE })
let cursor = 0
mongoose.connect(MONGO_URI)
.then(() => {
log('Parsing csv to objects...')
return new Promise((resolve, reject) => {
csv()
.fromStream(fs.createReadStream(CSV_FILE))
.subscribe((json) => {
cursor++
log(`Importing line: ${cursor}`)
return new Model(preprocess(json)).save()
}, reject, resolve)
})
})
.then(() => {
const runtime = (+new Date() - start) / 1000 / 60
log(`Done in ${runtime.toFixed(2)} minutes`)
process.exit(0)
})
.catch((err) => {
log(err)
process.exit(1)
})
function preprocess (json) {
// camelCase keys
json = _.mapKeys(json, (v, k) => _.camelCase(k))
let value
Object.keys(json).forEach((k) => {
value = json[k].trim()
if (value) {
if (k.toLowerCase().includes('date')) {
value = new Date(json[k])
} else if (isNumeric(json[k])) {
value = parseFloat(json[k], 10)
}
} else if (value === null || value === '') {
delete json[k]
return
}
json[k] = value
})
return json
}
function isNumeric (n) {
return !isNaN(n) && n !== ''
}