forked from medic/medic-bulk-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
update-embedded
executable file
·59 lines (52 loc) · 1.23 KB
/
update-embedded
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
#!/usr/bin/env node
var path = require('path');
var input = '',
stats = { docs: 0, updates: 0 },
docPath,
doc;
if (process.argv.length !== 3) {
console.error('Please provide the file system path to a doc.');
process.exit(1);
} else {
docPath = process.argv[2];
doc = require(path.resolve(docPath));
}
var isObject = function (obj) {
return Boolean(obj && typeof obj === 'object');
};
var updateEmbedded = function(data) {
Object.keys(data).forEach(function(k) {
if (data[k] && typeof data[k] === 'object') {
if (data[k]._id === doc._id) {
data[k] = doc;
stats.updates++;
} else {
updateEmbedded(data[k]);
}
}
});
};
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
input += chunk;
});
process.stdin.on('end', function () {
var data = JSON.parse(input);
if (data.docs) {
data = data.docs;
} else if (data.rows) {
data = data.rows;
} else if (!Array.isArray(data)) {
data = [data];
}
data.forEach(function(doc) {
// skip null values
if (!isObject(doc)) {
return;
}
stats.docs++;
updateEmbedded(doc.doc || doc);
});
process.stdout.write(JSON.stringify({docs: data}));
console.error(stats);
});