-
Notifications
You must be signed in to change notification settings - Fork 237
/
Copy pathmongodb.js
2588 lines (2338 loc) · 75.5 KB
/
mongodb.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright IBM Corp. 2012,2020. All Rights Reserved.
// Node module: loopback-connector-mongodb
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
/*!
* Module dependencies
*/
const g = require('strong-globalize')();
const mongodb = require('mongodb');
const urlParser = require('mongodb/lib/connection_string').parseOptions;
const util = require('util');
const async = require('async');
const Connector = require('loopback-connector').Connector;
const debug = require('debug')('loopback:connector:mongodb');
const Decimal128 = mongodb.Decimal128;
const Decimal128TypeRegex = /decimal128/i;
const ObjectIdValueRegex = /^[0-9a-fA-F]{24}$/;
const ObjectIdTypeRegex = /objectid/i;
exports.ObjectID = ObjectID;
/*!
* Convert the id to be a BSON ObjectID if it is compatible
* @param {*} id The id value
* @returns {ObjectID}
*/
function ObjectID(id) {
if (id instanceof mongodb.ObjectId) {
return id;
}
if (typeof id !== 'string') {
return id;
}
try {
// MongoDB's ObjectID constructor accepts number, 12-byte string or 24-byte
// hex string. For LoopBack, we only allow 24-byte hex string, but 12-byte
// string such as 'line-by-line' should be kept as string
if (ObjectIdValueRegex.test(id)) {
return new mongodb.ObjectId(id);
} else {
return id;
}
} catch (e) {
return id;
}
}
exports.generateMongoDBURL = generateMongoDBURL;
/*!
* Generate the mongodb URL from the options
*/
function generateMongoDBURL(options) {
// See https://docs.mongodb.com/manual/reference/connection-string/#dns-seedlist-connection-format
// It can be `mongodb+srv` now.
options.protocol = options.protocol || 'mongodb';
options.hostname = options.hostname || options.host || '127.0.0.1';
options.port = options.port || 27017;
options.database = options.database || options.db || 'test';
const username = options.username || options.user;
let portUrl = '';
// only include port if not using mongodb+srv
if (options.protocol !== 'mongodb+srv') {
portUrl = ':' + options.port;
}
if (username && options.password) {
return (
options.protocol +
'://' +
username +
':' +
options.password +
'@' +
options.hostname +
portUrl +
'/' +
options.database
);
} else {
return (
options.protocol +
'://' +
options.hostname +
portUrl +
'/' +
options.database
);
}
}
/**
* Initialize the MongoDB connector for the given data source
* @param {DataSource} dataSource The data source instance
* @param {Function} [callback] The callback function
*/
exports.initialize = function initializeDataSource(dataSource, callback) {
if (!mongodb) {
return;
}
const s = dataSource.settings;
s.safe = s.safe !== false;
s.w = s.w || 1;
s.writeConcern = s.writeConcern || {
w: s.w,
wtimeout: s.wtimeout || null,
j: s.j || null,
journal: s.journal || null,
fsync: s.fsync || null,
};
s.url = s.url || generateMongoDBURL(s);
// useNewUrlParser and useUnifiedTopology are default now
dataSource.connector = new MongoDB(s, dataSource);
dataSource.ObjectID = mongodb.ObjectId;
if (callback) {
if (s.lazyConnect) {
process.nextTick(function() {
callback();
});
} else {
dataSource.connector.connect(callback);
}
}
};
// MongoDB has deprecated some commands. To preserve
// compatibility of model connector hooks, this maps the new
// commands to previous names for the observors of this command.
const COMMAND_MAPPINGS = {
insertOne: 'insert',
updateOne: 'save',
findOneAndUpdate: 'findAndModify',
deleteOne: 'delete',
deleteMany: 'delete',
replaceOne: 'update',
updateMany: 'update',
countDocuments: 'count',
estimatedDocumentCount: 'count',
};
/**
* Helper function to be used in {@ fieldsArrayToObj} in order for V8 to avoid re-creating a new
* function every time {@ fieldsArrayToObj} is called
*
* @see fieldsArrayToObj
* @param {object} result
* @param {string} field
* @returns {object}
*/
function arrayToObjectReducer(result, field) {
result[field] = 1;
return result;
}
exports.fieldsArrayToObj = fieldsArrayToObj;
/**
* Helper function to accept an array representation of fields projection and return the mongo
* required object notation
*
* @param {string[]} fieldsArray
* @returns {Object}
*/
function fieldsArrayToObj(fieldsArray) {
if (!Array.isArray(fieldsArray)) return fieldsArray; // fail safe check in case non array object created
return fieldsArray.length ?
fieldsArray.reduce(arrayToObjectReducer, {}) :
{_id: 1};
}
exports.MongoDB = MongoDB;
/**
* The constructor for MongoDB connector
* @param {Object} settings The settings object
* @param {DataSource} dataSource The data source instance
* @constructor
*/
function MongoDB(settings, dataSource) {
Connector.call(this, 'mongodb', settings);
this.debug = settings.debug || debug.enabled;
if (this.debug) {
debug('Settings: %j', settings);
}
this.dataSource = dataSource;
if (
this.settings.enableOptimisedfindOrCreate === true ||
this.settings.enableOptimisedFindOrCreate === true ||
this.settings.enableOptimizedfindOrCreate === true ||
this.settings.enableOptimizedFindOrCreate === true
) {
debug('Optimized findOrCreate is enabled by default, and the enableOptimizedFindOrCreate setting ' +
'is ignored since v7.0.0.');
}
if (this.settings.enableGeoIndexing === true) {
MongoDB.prototype.buildNearFilter = buildNearFilter;
} else {
MongoDB.prototype.buildNearFilter = undefined;
}
}
util.inherits(MongoDB, Connector);
/**
* Connect to MongoDB
* @param {Function} [callback] The callback function
*
* @callback callback
* @param {Error} err The error object
* @param {Db} db The mongo DB object
*/
MongoDB.prototype.connect = function(callback) {
const self = this;
if (self.db) {
process.nextTick(function() {
if (callback) callback(null, self.db);
});
} else if (self.dataSource.connecting) {
self.dataSource.once('connected', function() {
process.nextTick(function() {
if (callback) callback(null, self.db);
});
});
} else {
// See https://www.mongodb.com/docs/manual/reference/connection-string
const validOptionNames = [
'replicaSet',
/** Enables or disables TLS/SSL for the connection. */
'tls',
/** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */
'ssl',
/**
* Specifies the location of a local TLS Certificate
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
*/
'tlsCertificateFile',
/** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key or only the client's TLS/SSL key when tlsCertificateFile is used to provide the certificate. */
'tlsCertificateKeyFile',
/** Specifies the password to de-crypt the tlsCertificateKeyFile. */
'tlsCertificateKeyFilePassword',
/** Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the mongod/mongos instance. */
'tlsCAFile',
/** Bypasses validation of the certificates presented by the mongod/mongos instance */
'tlsAllowInvalidCertificates',
/** Disables hostname validation of the certificate presented by the mongod/mongos instance. */
'tlsAllowInvalidHostnames',
/** Disables various certificate validations. */
'tlsInsecure',
/** The time in milliseconds to attempt a connection before timing out. */
'connectTimeoutMS',
/** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */
'socketTimeoutMS',
/** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */
'compressors',
/** An integer that specifies the compression level if using zlib for network compression. */
'zlibCompressionLevel',
/** The maximum number of hosts to connect to when using an srv connection string, a setting of `0` means unlimited hosts */
'srvMaxHosts',
/**
* Modifies the srv URI to look like:
*
* `_{srvServiceName}._tcp.{hostname}.{domainname}`
*
* Querying this DNS URI is expected to respond with SRV records
*/
'srvServiceName',
/** The maximum number of connections in the connection pool. */
'maxPoolSize',
/** The minimum number of connections in the connection pool. */
'minPoolSize',
/** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */
'maxConnecting',
/** The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. */
'maxIdleTimeMS',
/** The maximum time in milliseconds that a thread can wait for a connection to become available. */
'waitQueueTimeoutMS',
/** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */
'readConcern',
/** The level of isolation */
'readConcernLevel',
/** Specifies the read preferences for this connection */
'readPreference',
/** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */
'maxStalenessSeconds',
/** Specifies the tags document as a comma-separated list of colon-separated key-value pairs. */
'readPreferenceTags',
/** The auth settings for when connection to server. */
'auth',
/** Specify the database name associated with the user’s credentials. */
'authSource',
/** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */
'authMechanism',
/** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */
'authMechanismProperties',
/** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */
'localThresholdMS',
/** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */
'serverSelectionTimeoutMS',
/** heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one. */
'heartbeatFrequencyMS',
/** Sets the minimum heartbeat frequency. In the event that the driver has to frequently re-check a server's availability, it will wait at least this long since the previous check to avoid wasted effort. */
'minHeartbeatFrequencyMS',
/** The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections */
'appName',
/** Enables retryable reads. */
'retryReads',
/** Enable retryable writes. */
'retryWrites',
/** Allow a driver to force a Single topology type with a connection string containing one host */
'directConnection',
/** Instruct the driver it is connecting to a load balancer fronting a mongos like service */
'loadBalanced',
/**
* The write concern w value
* @deprecated Please use the `writeConcern` option instead
*/
'w',
/**
* The write concern timeout
* @deprecated Please use the `writeConcern` option instead
*/
'wtimeoutMS',
/**
* The journal write concern
* @deprecated Please use the `writeConcern` option instead
*/
'journal',
/**
* A MongoDB WriteConcern, which describes the level of acknowledgement
* requested from MongoDB for write operations.
*
* @see https://www.mongodb.com/docs/manual/reference/write-concern/
*/
'writeConcern',
/**
* Validate mongod server certificate against Certificate Authority
* @deprecated Will be removed in the next major version. Please use tlsAllowInvalidCertificates instead.
*/
'sslValidate',
/**
* SSL Certificate file path.
* @deprecated Will be removed in the next major version. Please use tlsCAFile instead.
*/
'sslCA',
/**
* SSL Certificate file path.
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
*/
'sslCert',
/**
* SSL Key file file path.
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
*/
'sslKey',
/**
* SSL Certificate pass phrase.
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFilePassword instead.
*/
'sslPass',
/**
* SSL Certificate revocation list file path.
* @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
*/
'sslCRL',
/** TCP Connection no delay */
'noDelay',
/** @deprecated TCP Connection keep alive enabled. Will not be able to turn off in the future. */
'keepAlive',
/**
* @deprecated The number of milliseconds to wait before initiating keepAlive on the TCP socket.
* Will not be configurable in the future.
*/
'keepAliveInitialDelay',
/** Force server to assign `_id` values instead of driver */
'forceServerObjectId',
/** A primary key factory function for generation of custom `_id` keys */
'pkFactory',
/** Enable command monitoring for this client */
'monitorCommands',
/** Server API version */
'serverApi',
/**
* Optionally enable in-use auto encryption
*
* @remarks
* Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error
* (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts.
*
* Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://www.mongodb.com/docs/manual/reference/command/listCollections/#dbcmd.listCollections).
*
* If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true:
* - AutoEncryptionOptions.keyVaultClient is not passed.
* - AutoEncryptionOptions.bypassAutomaticEncryption is false.
*
* If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted.
*/
'autoEncryption',
/** Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver */
'driverInfo',
/** Configures a Socks5 proxy host used for creating TCP connections. */
'proxyHost',
/** Configures a Socks5 proxy port used for creating TCP connections. */
'proxyPort',
/** Configures a Socks5 proxy username when the proxy in proxyHost requires username/password authentication. */
'proxyUsername',
/** Configures a Socks5 proxy password when the proxy in proxyHost requires username/password authentication. */
'proxyPassword',
];
const lbOptions = Object.keys(self.settings);
const validOptions = {};
lbOptions.forEach(function(option) {
if (validOptionNames.indexOf(option) > -1) {
validOptions[option] = self.settings[option];
}
});
debug('Valid options: %j', validOptions);
function onError(err) {
/* istanbul ignore if */
if (self.debug) {
g.error(
'{{MongoDB}} connection is failed: %s %s',
self.settings.url,
err,
);
}
if (callback) callback(err);
}
const urlObj = new URL(self.settings.url);
if ((urlObj.pathname === '' ||
urlObj.pathname.split('/')[1] === '') &&
typeof self.settings.database === 'string') {
urlObj.pathname = self.settings.database;
self.settings.url = urlObj.toString();
}
const mongoClient = new mongodb.MongoClient(self.settings.url, validOptions);
const callbackConnect = util.callbackify(() => mongoClient.connect());
callbackConnect(function(
err,
client,
) {
if (err) {
onError(err);
return;
}
if (self.debug) {
debug('MongoDB connection is established: ' + self.settings.url);
}
self.client = client;
// The database name might be in the url
try {
const url = urlParser(self.settings.url, validOptions); // only supports the validURL options now
// See https://github.com/mongodb/mongodb/blob/6.0.1/lib/mongodb.d.ts#L3854
const validDbOptionNames = [
'authSource',
'forceServerObjectId',
'readPreference',
'pkFactory',
'readConcern',
'retryWrites',
'checkKeys',
'serializeFunctions',
'ignoreUndefined',
'promoteLongs',
'promoteBuffers',
'promoteValues',
'fieldsAsRaw',
'bsonRegExp',
'raw',
'writeConcern',
'logger',
'loggerLevel',
];
const dbOptions = url.db_options || self.settings;
const dbOptionKeys = Object.keys(dbOptions);
const validDbOptions = {};
dbOptionKeys.forEach(function(option) {
if (validDbOptionNames.indexOf(option) > -1) {
validDbOptions[option] = dbOptions[option];
}
});
self.db = client.db(
url.dbName || self.settings.database,
validDbOptions,
);
if (callback) callback(err, self.db);
} catch (e) {
onError(e);
}
});
}
};
MongoDB.prototype.getTypes = function() {
return ['db', 'nosql', 'mongodb'];
};
MongoDB.prototype.getDefaultIdType = function() {
return ObjectID;
};
/**
* Get collection name for a given model
* @param {String} modelName The model name
* @returns {String} collection name
*/
MongoDB.prototype.collectionName = function(modelName) {
const modelClass = this._models[modelName];
if (modelClass && modelClass.settings && modelClass.settings.mongodb) {
modelName = modelClass.settings.mongodb.collection || modelName;
}
return modelName;
};
/**
* Access a MongoDB collection by model name
* @param {String} modelName The model name
* @returns {*}
*/
MongoDB.prototype.collection = function(modelName) {
if (!this.db) {
throw new Error(g.f('{{MongoDB}} connection is not established'));
}
const collectionName = this.collectionName(modelName);
return this.db.collection(collectionName);
};
/*!
* Convert the data from database to JSON
*
* @param {String} modelName The model name
* @param {Object} data The data from DB
*/
MongoDB.prototype.fromDatabase = function(modelName, data) {
if (!data) {
return null;
}
const modelInfo = this._models[modelName] || this.dataSource.modelBuilder.definitions[modelName];
const props = modelInfo.properties;
for (const p in props) {
const prop = props[p];
if (prop && prop.type === Buffer) {
if (data[p] instanceof mongodb.Binary) {
// Convert the Binary into Buffer
data[p] = data[p].read(0, data[p].length());
}
} else if (prop && prop.type === String) {
if (data[p] instanceof mongodb.Binary) {
// Convert the Binary into String
data[p] = data[p].toString();
}
} else if (
data[p] &&
prop &&
prop.type &&
prop.type.name === 'GeoPoint' &&
this.settings.enableGeoIndexing === true
) {
data[p] = {
lat: data[p].coordinates[1],
lng: data[p].coordinates[0],
};
} else if (data[p] && prop && prop.type.definition) {
data[p] = this.fromDatabase(prop.type.definition.name, data[p]);
}
}
data = this.fromDatabaseToPropertyNames(modelName, data);
return data;
};
/*!
* Convert JSON to database-appropriate format
*
* @param {String} modelName The model name
* @param {Object} data The JSON data to convert
*/
MongoDB.prototype.toDatabase = function(modelName, data) {
const modelCtor = this._models[modelName];
const props = modelCtor.properties;
if (this.settings.enableGeoIndexing !== true) {
visitAllProperties(data, modelCtor, coercePropertyValue);
// Override custom column names
data = this.fromPropertyToDatabaseNames(modelName, data);
return data;
}
for (const p in props) {
const prop = props[p];
const isGeoPoint = data[p] && prop && prop.type && prop.type.name === 'GeoPoint';
if (isGeoPoint) {
data[p] = {
coordinates: [data[p].lng, data[p].lat],
type: 'Point',
};
}
}
visitAllProperties(data, modelCtor, coercePropertyValue);
// Override custom column names
data = this.fromPropertyToDatabaseNames(modelName, data);
if (debug.enabled) debug('toDatabase data: ', util.inspect(data));
return data;
};
/**
* Execute a mongodb command
* @param {String} modelName The model name
* @param {String} command The command name
* @param [...] params Parameters for the given command
*/
MongoDB.prototype.execute = function(modelName, command) {
const self = this;
// Get the parameters for the given command
const args = [].slice.call(arguments, 2);
// The last argument must be a callback function
const callback = args[args.length - 1];
// Topology is destroyed when the server is disconnected
// Execute if DB is connected and functional otherwise connect/reconnect first
if (
self.db && (
!self.db.topology || (self.db.topology && !self.db.topology.isDestroyed())
)
) {
doExecute();
} else if (self.db && !self.db.topology) {
doExecute();
} else {
if (self.db) {
self.disconnect();
self.db = null;
}
self.connect(function(err, db) {
if (err) {
debug(
'Connection not established - MongoDB: model=%s command=%s -- error=%s',
modelName,
command,
err,
);
}
doExecute();
});
}
function doExecute() {
let collection;
const context = Object.assign({}, {
model: modelName,
collection: collection,
req: {
command: command,
params: args,
},
});
try {
collection = self.collection(modelName);
} catch (err) {
debug('Error: ', err);
callback(err);
return;
}
if (command in COMMAND_MAPPINGS) {
context.req.command = COMMAND_MAPPINGS[command];
}
self.notifyObserversAround(
'execute',
context,
function(context, done) {
const observerCallback = function(err, result) {
if (err) {
debug('Error: ', err);
} else {
context.res = result;
debug('Result: ', result);
}
done(err, result);
};
// from mongoddb v5 command does not support callback
args.pop();
debug('MongoDB: model=%s command=%s', modelName, command, args);
// args had callback removed
try {
const execute = collection[command].apply(collection, args);
if (command === 'find') {
return observerCallback(null, execute);
} else {
const callbackCommand = util.callbackify(() => execute);
return callbackCommand(observerCallback);
}
} catch (err) {
return observerCallback(err, null);
}
},
callback,
);
}
};
MongoDB.prototype.coerceId = function(modelName, id, options) {
// See https://github.com/strongloop/loopback-connector-mongodb/issues/206
if (id == null) return id;
const self = this;
let idValue = id;
const idName = self.idName(modelName);
// Type conversion for id
const idProp = self.getPropertyDefinition(modelName, idName);
if (idProp && typeof idProp.type === 'function') {
if (!(idValue instanceof idProp.type)) {
idValue = idProp.type(id);
if (idProp.type === Number && isNaN(id)) {
// Reset to id
idValue = id;
}
}
const modelCtor = this._models[modelName];
idValue = coerceToObjectId(modelCtor, idProp, idValue);
}
return idValue;
};
/**
* Create a new model instance for the given data
* @param {String} modelName The model name
* @param {Object} data The model data
* @param {Function} [callback] The callback function
*/
MongoDB.prototype.create = function(modelName, data, options, callback) {
const self = this;
if (self.debug) {
debug('create', modelName, data);
}
let idValue = self.getIdValue(modelName, data);
const idName = self.idName(modelName);
if (idValue === null) {
delete data[idName]; // Allow MongoDB to generate the id
} else {
const oid = self.coerceId(modelName, idValue, options); // Is it an Object ID?c
data._id = oid; // Set it to _id
if (idName !== '_id') {
delete data[idName];
}
}
data = self.toDatabase(modelName, data);
this.execute(modelName, 'insertOne', data, buildOptions({safe: true},
options), function(err, result) {
if (self.debug) {
debug('create.callback', modelName, err, result);
}
if (err) {
return callback(err);
}
idValue = result.insertedId;
try {
idValue = self.coerceId(modelName, idValue, options);
} catch (err) {
return callback(err);
}
// Wrap it to process.nextTick as delete data._id seems to be interferring
// with mongo insert
process.nextTick(function() {
// Restore the data object
delete data._id;
data[idName] = idValue;
callback(err, err ? null : idValue);
});
});
};
/**
* Save the model instance for the given data
* @param {String} modelName The model name
* @param {Object} data The model data
* @param {Function} [callback] The callback function
*/
MongoDB.prototype.save = function(modelName, data, options, callback) {
const self = this;
if (self.debug) {
debug('save', modelName, data);
}
const idValue = self.getIdValue(modelName, data);
const idName = self.idName(modelName);
const oid = self.coerceId(modelName, idValue, options);
data._id = oid;
if (idName !== '_id') {
delete data[idName];
}
data = self.toDatabase(modelName, data);
this.execute(modelName, 'updateOne', {_id: oid}, {$set: data}, buildOptions({upsert: true},
options), function(err, result) {
if (!err) {
self.setIdValue(modelName, data, idValue);
if (idName !== '_id') {
delete data._id;
}
}
if (self.debug) {
debug('save.callback', modelName, err, result);
}
const info = {};
if (result) {
// new 4.0 result formats:
// { acknowledged: true, modifiedCount: 1, upsertedCount: 1, : modifiedCount: 1}
if (result.acknowledged === true && (result.matchedCount === 1 || result.upsertedCount === 1)) {
info.isNewInstance = result.upsertedCount === 1;
} else {
debug('save result format not recognized: %j', result);
}
}
if (callback) {
callback(err, result && result.ops, info);
}
});
};
/**
* Check if a model instance exists by id
* @param {String} modelName The model name
* @param {*} id The id value
* @param {Function} [callback] The callback function
*
*/
MongoDB.prototype.exists = function(modelName, id, options, callback) {
const self = this;
if (self.debug) {
debug('exists', modelName, id);
}
id = self.coerceId(modelName, id, options);
this.execute(modelName, 'findOne', {_id: id}, buildOptions({}, options), function(err, data) {
if (self.debug) {
debug('exists.callback', modelName, id, err, data);
}
callback(err, !!(!err && data));
});
};
/**
* Find a model instance by id
* @param {String} modelName The model name
* @param {*} id The id value
* @param {Function} [callback] The callback function
*/
MongoDB.prototype.find = function find(modelName, id, options, callback) {
const self = this;
if (self.debug) {
debug('find', modelName, id);
}
const idName = self.idName(modelName);
const oid = self.coerceId(modelName, id, options);
this.execute(modelName, 'findOne', {_id: oid}, buildOptions({}, options), function(err, data) {
if (self.debug) {
debug('find.callback', modelName, id, err, data);
}
data = self.fromDatabase(modelName, data);
if (data && idName !== '_id') {
delete data._id;
}
if (callback) {
callback(err, data);
}
});
};
Connector.defineAliases(MongoDB.prototype, 'find', 'findById');
/**
* Parses the data input for update operations and returns the
* sanitised version of the object.
*
* @param data
* @returns {*}
*/
MongoDB.prototype.parseUpdateData = function(modelName, data, options) {
options = options || {};
const parsedData = {};
const modelClass = this._models[modelName];
let allowExtendedOperators = this.settings.allowExtendedOperators;
if (options.hasOwnProperty('allowExtendedOperators')) {
allowExtendedOperators = options.allowExtendedOperators === true;
} else if (
allowExtendedOperators !== false &&
modelClass.settings.mongodb &&
modelClass.settings.mongodb.hasOwnProperty('allowExtendedOperators')
) {
allowExtendedOperators =
modelClass.settings.mongodb.allowExtendedOperators === true;
} else if (allowExtendedOperators === true) {
allowExtendedOperators = true;
}
if (allowExtendedOperators) {
// Check for other operators and sanitize the data obj
const acceptedOperators = [
// Field operators
'$currentDate',
'$inc',
'$max',
'$min',
'$mul',
'$rename',
'$setOnInsert',
'$set',
'$unset',
// Array operators
'$addToSet',
'$pop',
'$pullAll',
'$pull',
'$push',
// Bitwise operator
'$bit',
];
let usedOperators = 0;
// each accepted operator will take its place on parsedData if defined
for (let i = 0; i < acceptedOperators.length; i++) {
if (data[acceptedOperators[i]]) {
parsedData[acceptedOperators[i]] = data[acceptedOperators[i]];
usedOperators++;
}
}
// if parsedData is still empty, then we fallback to $set operator
if (usedOperators === 0 && Object.keys(data).length > 0) {
parsedData.$set = data;
}
} else if (Object.keys(data).length > 0) {
parsedData.$set = data;
}
return parsedData;
};
/**
* Update if the model instance exists with the same id or create a new instance
*
* @param {String} modelName The model name
* @param {Object} data The model instance data
* @param {Function} [callback] The callback function
*/
MongoDB.prototype.updateOrCreate = function updateOrCreate(
modelName,
data,
options,
callback,
) {
const self = this;
if (self.debug) {
debug('updateOrCreate', modelName, data);
}
const id = self.getIdValue(modelName, data);
const idName = self.idName(modelName);
const oid = self.coerceId(modelName, id, options);
delete data[idName];
data = self.toDatabase(modelName, data);
// Check for other operators and sanitize the data obj
data = self.parseUpdateData(modelName, data, options);