db.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.Db = void 0;
  4. const admin_1 = require("./admin");
  5. const bson_1 = require("./bson");
  6. const change_stream_1 = require("./change_stream");
  7. const collection_1 = require("./collection");
  8. const CONSTANTS = require("./constants");
  9. const aggregation_cursor_1 = require("./cursor/aggregation_cursor");
  10. const error_1 = require("./error");
  11. const logger_1 = require("./logger");
  12. const add_user_1 = require("./operations/add_user");
  13. const collections_1 = require("./operations/collections");
  14. const create_collection_1 = require("./operations/create_collection");
  15. const drop_1 = require("./operations/drop");
  16. const execute_operation_1 = require("./operations/execute_operation");
  17. const indexes_1 = require("./operations/indexes");
  18. const list_collections_1 = require("./operations/list_collections");
  19. const profiling_level_1 = require("./operations/profiling_level");
  20. const remove_user_1 = require("./operations/remove_user");
  21. const rename_1 = require("./operations/rename");
  22. const run_command_1 = require("./operations/run_command");
  23. const set_profiling_level_1 = require("./operations/set_profiling_level");
  24. const stats_1 = require("./operations/stats");
  25. const read_concern_1 = require("./read_concern");
  26. const read_preference_1 = require("./read_preference");
  27. const utils_1 = require("./utils");
  28. const write_concern_1 = require("./write_concern");
  29. // Allowed parameters
  30. const DB_OPTIONS_ALLOW_LIST = [
  31. 'writeConcern',
  32. 'readPreference',
  33. 'readPreferenceTags',
  34. 'native_parser',
  35. 'forceServerObjectId',
  36. 'pkFactory',
  37. 'serializeFunctions',
  38. 'raw',
  39. 'authSource',
  40. 'ignoreUndefined',
  41. 'readConcern',
  42. 'retryMiliSeconds',
  43. 'numberOfRetries',
  44. 'loggerLevel',
  45. 'logger',
  46. 'promoteBuffers',
  47. 'promoteLongs',
  48. 'bsonRegExp',
  49. 'enableUtf8Validation',
  50. 'promoteValues',
  51. 'compression',
  52. 'retryWrites'
  53. ];
  54. /**
  55. * The **Db** class is a class that represents a MongoDB Database.
  56. * @public
  57. *
  58. * @example
  59. * ```js
  60. * const { MongoClient } = require('mongodb');
  61. * // Connection url
  62. * const url = 'mongodb://localhost:27017';
  63. * // Database Name
  64. * const dbName = 'test';
  65. * // Connect using MongoClient
  66. * MongoClient.connect(url, function(err, client) {
  67. * // Select the database by name
  68. * const testDb = client.db(dbName);
  69. * client.close();
  70. * });
  71. * ```
  72. */
  73. class Db {
  74. /**
  75. * Creates a new Db instance
  76. *
  77. * @param client - The MongoClient for the database.
  78. * @param databaseName - The name of the database this instance represents.
  79. * @param options - Optional settings for Db construction
  80. */
  81. constructor(client, databaseName, options) {
  82. var _a;
  83. options = options !== null && options !== void 0 ? options : {};
  84. // Filter the options
  85. options = (0, utils_1.filterOptions)(options, DB_OPTIONS_ALLOW_LIST);
  86. // Ensure we have a valid db name
  87. validateDatabaseName(databaseName);
  88. // Internal state of the db object
  89. this.s = {
  90. // Client
  91. client,
  92. // Options
  93. options,
  94. // Logger instance
  95. logger: new logger_1.Logger('Db', options),
  96. // Unpack read preference
  97. readPreference: read_preference_1.ReadPreference.fromOptions(options),
  98. // Merge bson options
  99. bsonOptions: (0, bson_1.resolveBSONOptions)(options, client),
  100. // Set up the primary key factory or fallback to ObjectId
  101. pkFactory: (_a = options === null || options === void 0 ? void 0 : options.pkFactory) !== null && _a !== void 0 ? _a : utils_1.DEFAULT_PK_FACTORY,
  102. // ReadConcern
  103. readConcern: read_concern_1.ReadConcern.fromOptions(options),
  104. writeConcern: write_concern_1.WriteConcern.fromOptions(options),
  105. // Namespace
  106. namespace: new utils_1.MongoDBNamespace(databaseName)
  107. };
  108. }
  109. get databaseName() {
  110. return this.s.namespace.db;
  111. }
  112. // Options
  113. get options() {
  114. return this.s.options;
  115. }
  116. /**
  117. * slaveOk specified
  118. * @deprecated Use secondaryOk instead
  119. */
  120. get slaveOk() {
  121. return this.secondaryOk;
  122. }
  123. /**
  124. * Check if a secondary can be used (because the read preference is *not* set to primary)
  125. */
  126. get secondaryOk() {
  127. var _a;
  128. return ((_a = this.s.readPreference) === null || _a === void 0 ? void 0 : _a.preference) !== 'primary' || false;
  129. }
  130. get readConcern() {
  131. return this.s.readConcern;
  132. }
  133. /**
  134. * The current readPreference of the Db. If not explicitly defined for
  135. * this Db, will be inherited from the parent MongoClient
  136. */
  137. get readPreference() {
  138. if (this.s.readPreference == null) {
  139. return this.s.client.readPreference;
  140. }
  141. return this.s.readPreference;
  142. }
  143. get bsonOptions() {
  144. return this.s.bsonOptions;
  145. }
  146. // get the write Concern
  147. get writeConcern() {
  148. return this.s.writeConcern;
  149. }
  150. get namespace() {
  151. return this.s.namespace.toString();
  152. }
  153. createCollection(name, options, callback) {
  154. if (typeof options === 'function')
  155. (callback = options), (options = {});
  156. return (0, execute_operation_1.executeOperation)(this.s.client, new create_collection_1.CreateCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)), callback);
  157. }
  158. command(command, options, callback) {
  159. if (typeof options === 'function')
  160. (callback = options), (options = {});
  161. // Intentionally, we do not inherit options from parent for this operation.
  162. return (0, execute_operation_1.executeOperation)(this.s.client, new run_command_1.RunCommandOperation(this, command, options !== null && options !== void 0 ? options : {}), callback);
  163. }
  164. /**
  165. * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6
  166. *
  167. * @param pipeline - An array of aggregation stages to be executed
  168. * @param options - Optional settings for the command
  169. */
  170. aggregate(pipeline = [], options) {
  171. if (arguments.length > 2) {
  172. throw new error_1.MongoInvalidArgumentError('Method "db.aggregate()" accepts at most two arguments');
  173. }
  174. if (typeof pipeline === 'function') {
  175. throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must not be function');
  176. }
  177. if (typeof options === 'function') {
  178. throw new error_1.MongoInvalidArgumentError('Argument "options" must not be function');
  179. }
  180. return new aggregation_cursor_1.AggregationCursor(this.s.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options));
  181. }
  182. /** Return the Admin db instance */
  183. admin() {
  184. return new admin_1.Admin(this);
  185. }
  186. /**
  187. * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.
  188. *
  189. * @param name - the collection name we wish to access.
  190. * @returns return the new Collection instance
  191. */
  192. collection(name, options = {}) {
  193. if (typeof options === 'function') {
  194. throw new error_1.MongoInvalidArgumentError('The callback form of this helper has been removed.');
  195. }
  196. const finalOptions = (0, utils_1.resolveOptions)(this, options);
  197. return new collection_1.Collection(this, name, finalOptions);
  198. }
  199. stats(options, callback) {
  200. if (typeof options === 'function')
  201. (callback = options), (options = {});
  202. return (0, execute_operation_1.executeOperation)(this.s.client, new stats_1.DbStatsOperation(this, (0, utils_1.resolveOptions)(this, options)), callback);
  203. }
  204. listCollections(filter = {}, options = {}) {
  205. return new list_collections_1.ListCollectionsCursor(this, filter, (0, utils_1.resolveOptions)(this, options));
  206. }
  207. renameCollection(fromCollection, toCollection, options, callback) {
  208. if (typeof options === 'function')
  209. (callback = options), (options = {});
  210. // Intentionally, we do not inherit options from parent for this operation.
  211. options = { ...options, readPreference: read_preference_1.ReadPreference.PRIMARY };
  212. // Add return new collection
  213. options.new_collection = true;
  214. return (0, execute_operation_1.executeOperation)(this.s.client, new rename_1.RenameOperation(this.collection(fromCollection), toCollection, options), callback);
  215. }
  216. dropCollection(name, options, callback) {
  217. if (typeof options === 'function')
  218. (callback = options), (options = {});
  219. return (0, execute_operation_1.executeOperation)(this.s.client, new drop_1.DropCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)), callback);
  220. }
  221. dropDatabase(options, callback) {
  222. if (typeof options === 'function')
  223. (callback = options), (options = {});
  224. return (0, execute_operation_1.executeOperation)(this.s.client, new drop_1.DropDatabaseOperation(this, (0, utils_1.resolveOptions)(this, options)), callback);
  225. }
  226. collections(options, callback) {
  227. if (typeof options === 'function')
  228. (callback = options), (options = {});
  229. return (0, execute_operation_1.executeOperation)(this.s.client, new collections_1.CollectionsOperation(this, (0, utils_1.resolveOptions)(this, options)), callback);
  230. }
  231. createIndex(name, indexSpec, options, callback) {
  232. if (typeof options === 'function')
  233. (callback = options), (options = {});
  234. return (0, execute_operation_1.executeOperation)(this.s.client, new indexes_1.CreateIndexOperation(this, name, indexSpec, (0, utils_1.resolveOptions)(this, options)), callback);
  235. }
  236. addUser(username, password, options, callback) {
  237. if (typeof password === 'function') {
  238. (callback = password), (password = undefined), (options = {});
  239. }
  240. else if (typeof password !== 'string') {
  241. if (typeof options === 'function') {
  242. (callback = options), (options = password), (password = undefined);
  243. }
  244. else {
  245. (options = password), (callback = undefined), (password = undefined);
  246. }
  247. }
  248. else {
  249. if (typeof options === 'function')
  250. (callback = options), (options = {});
  251. }
  252. return (0, execute_operation_1.executeOperation)(this.s.client, new add_user_1.AddUserOperation(this, username, password, (0, utils_1.resolveOptions)(this, options)), callback);
  253. }
  254. removeUser(username, options, callback) {
  255. if (typeof options === 'function')
  256. (callback = options), (options = {});
  257. return (0, execute_operation_1.executeOperation)(this.s.client, new remove_user_1.RemoveUserOperation(this, username, (0, utils_1.resolveOptions)(this, options)), callback);
  258. }
  259. setProfilingLevel(level, options, callback) {
  260. if (typeof options === 'function')
  261. (callback = options), (options = {});
  262. return (0, execute_operation_1.executeOperation)(this.s.client, new set_profiling_level_1.SetProfilingLevelOperation(this, level, (0, utils_1.resolveOptions)(this, options)), callback);
  263. }
  264. profilingLevel(options, callback) {
  265. if (typeof options === 'function')
  266. (callback = options), (options = {});
  267. return (0, execute_operation_1.executeOperation)(this.s.client, new profiling_level_1.ProfilingLevelOperation(this, (0, utils_1.resolveOptions)(this, options)), callback);
  268. }
  269. indexInformation(name, options, callback) {
  270. if (typeof options === 'function')
  271. (callback = options), (options = {});
  272. return (0, execute_operation_1.executeOperation)(this.s.client, new indexes_1.IndexInformationOperation(this, name, (0, utils_1.resolveOptions)(this, options)), callback);
  273. }
  274. /**
  275. * Unref all sockets
  276. * @deprecated This function is deprecated and will be removed in the next major version.
  277. */
  278. unref() {
  279. (0, utils_1.getTopology)(this).unref();
  280. }
  281. /**
  282. * Create a new Change Stream, watching for new changes (insertions, updates,
  283. * replacements, deletions, and invalidations) in this database. Will ignore all
  284. * changes to system collections.
  285. *
  286. * @remarks
  287. * watch() accepts two generic arguments for distinct usecases:
  288. * - The first is to provide the schema that may be defined for all the collections within this database
  289. * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument
  290. *
  291. * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
  292. * @param options - Optional settings for the command
  293. * @typeParam TSchema - Type of the data being detected by the change stream
  294. * @typeParam TChange - Type of the whole change stream document emitted
  295. */
  296. watch(pipeline = [], options = {}) {
  297. // Allow optionally not specifying a pipeline
  298. if (!Array.isArray(pipeline)) {
  299. options = pipeline;
  300. pipeline = [];
  301. }
  302. return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options));
  303. }
  304. /** Return the db logger */
  305. getLogger() {
  306. return this.s.logger;
  307. }
  308. get logger() {
  309. return this.s.logger;
  310. }
  311. }
  312. exports.Db = Db;
  313. Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION;
  314. Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION;
  315. Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION;
  316. Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION;
  317. Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION;
  318. Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION;
  319. // TODO(NODE-3484): Refactor into MongoDBNamespace
  320. // Validate the database name
  321. function validateDatabaseName(databaseName) {
  322. if (typeof databaseName !== 'string')
  323. throw new error_1.MongoInvalidArgumentError('Database name must be a string');
  324. if (databaseName.length === 0)
  325. throw new error_1.MongoInvalidArgumentError('Database name cannot be the empty string');
  326. if (databaseName === '$external')
  327. return;
  328. const invalidChars = [' ', '.', '$', '/', '\\'];
  329. for (let i = 0; i < invalidChars.length; i++) {
  330. if (databaseName.indexOf(invalidChars[i]) !== -1)
  331. throw new error_1.MongoAPIError(`database names cannot contain the character '${invalidChars[i]}'`);
  332. }
  333. }
  334. //# sourceMappingURL=db.js.map