forked from adamreisnz/mongoose-upsert-many
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (71 loc) · 2.05 KB
/
index.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
88
89
90
'use strict';
/**
* Load helpers
*/
const parseItem = require('./helpers/parse-item');
const matchCriteria = require('./helpers/match-criteria');
/**
* Apply bulk upsert helper to schema
*/
module.exports = function upsertMany(schema) {
//Extract schema wide config
const defaults = Object.assign({
matchFields: ['_id'],
type: 'updateOne',
ensureModel: false,
toObjectConfig: {
depopulate: true,
versionKey: false,
},
ordered: true,
}, schema.options.upsertMany || {});
//Create helper
schema.statics.upsertMany = function(items, config) {
//Merge config
config = Object.assign({}, defaults, config || {});
//Get config
const {type} = config;
const upsert = true;
//Use default match fields if none provided
let {matchFields} = config;
if (!Array.isArray(matchFields) || matchFields.length === 0) {
matchFields = ['_id'];
}
//Create bulk operations
const ops = items
.map(item => {
//Parse item
item = parseItem(item, this, config);
//Extract match criteria
const filter = matchCriteria(item, matchFields);
//Can't have _id field when upserting item
if (typeof item._id !== 'undefined') {
delete item._id;
}
//Check type
switch (type) {
//Insert op
case 'insertOne':
return {[type]: {document: item}};
//Update op
case 'updateOne':
case 'updateMany':
return {[type]: {filter, upsert, update: item}};
//Delete op
case 'deleteOne':
case 'deleteMany':
return {[type]: {filter}};
//Replace op
case 'replaceOne':
return {[type]: {filter, upsert, replacement: item}};
//Unknown
default:
throw new Error(`Unsupported bulkOp type: ${type}`);
}
});
//Retrieve if bulkWrite should be a ordered or unordered write
let {ordered} = config;
//Bulk write
return this.bulkWrite(ops, {ordered});
};
};