-
Notifications
You must be signed in to change notification settings - Fork 0
/
addToDb.js
39 lines (36 loc) · 1 KB
/
addToDb.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
("use strict");
/**
* @desc Adds array of JS objects to a MongoDB collection
* @param {Array<Object>} $documents
* @param {MongoClient.Db.collection} $collection
* @return {Object} { nSuccess: Array<ing>, nFail: Array<int>, nFailByCodename: Array<MongoError.codeName> }
*/
module.exports = async ({ documents = [], collection = null }) => {
let nSuccess = 0;
let nFail = 0;
const nFailByCodeName = {};
const add = (codeName) => {
if (!nFailByCodeName[codeName]) {
nFailByCodeName[codeName] = 1;
} else {
nFailByCodeName[codeName] += 1;
}
};
return Promise.all(
Object.keys(documents)
.map((v) => v + 1)
.map(async (num, i) => {
await collection
.findOneAndReplace({ Num: +num }, documents[i], {
upsert: true,
})
.then(() => (nSuccess += 1))
.catch((e) => {
nFail += 1;
add(e.codeName);
});
})
).then((_) => {
return { nSuccess, nFail, nFailByCodeName };
});
};