db.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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 list_collections_cursor_1 = require("./cursor/list_collections_cursor");
  11. const run_command_cursor_1 = require("./cursor/run_command_cursor");
  12. const error_1 = require("./error");
  13. const create_collection_1 = require("./operations/create_collection");
  14. const drop_1 = require("./operations/drop");
  15. const execute_operation_1 = require("./operations/execute_operation");
  16. const indexes_1 = require("./operations/indexes");
  17. const profiling_level_1 = require("./operations/profiling_level");
  18. const remove_user_1 = require("./operations/remove_user");
  19. const rename_1 = require("./operations/rename");
  20. const run_command_1 = require("./operations/run_command");
  21. const set_profiling_level_1 = require("./operations/set_profiling_level");
  22. const stats_1 = require("./operations/stats");
  23. const read_concern_1 = require("./read_concern");
  24. const read_preference_1 = require("./read_preference");
  25. const utils_1 = require("./utils");
  26. const write_concern_1 = require("./write_concern");
  27. // Allowed parameters
  28. const DB_OPTIONS_ALLOW_LIST = [
  29. 'writeConcern',
  30. 'readPreference',
  31. 'readPreferenceTags',
  32. 'native_parser',
  33. 'forceServerObjectId',
  34. 'pkFactory',
  35. 'serializeFunctions',
  36. 'raw',
  37. 'authSource',
  38. 'ignoreUndefined',
  39. 'readConcern',
  40. 'retryMiliSeconds',
  41. 'numberOfRetries',
  42. 'useBigInt64',
  43. 'promoteBuffers',
  44. 'promoteLongs',
  45. 'bsonRegExp',
  46. 'enableUtf8Validation',
  47. 'promoteValues',
  48. 'compression',
  49. 'retryWrites',
  50. 'timeoutMS'
  51. ];
  52. /**
  53. * The **Db** class is a class that represents a MongoDB Database.
  54. * @public
  55. *
  56. * @example
  57. * ```ts
  58. * import { MongoClient } from 'mongodb';
  59. *
  60. * interface Pet {
  61. * name: string;
  62. * kind: 'dog' | 'cat' | 'fish';
  63. * }
  64. *
  65. * const client = new MongoClient('mongodb://localhost:27017');
  66. * const db = client.db();
  67. *
  68. * // Create a collection that validates our union
  69. * await db.createCollection<Pet>('pets', {
  70. * validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } }
  71. * })
  72. * ```
  73. */
  74. class Db {
  75. /**
  76. * Creates a new Db instance.
  77. *
  78. * Db name cannot contain a dot, the server may apply more restrictions when an operation is run.
  79. *
  80. * @param client - The MongoClient for the database.
  81. * @param databaseName - The name of the database this instance represents.
  82. * @param options - Optional settings for Db construction.
  83. */
  84. constructor(client, databaseName, options) {
  85. options = options ?? {};
  86. // Filter the options
  87. options = (0, utils_1.filterOptions)(options, DB_OPTIONS_ALLOW_LIST);
  88. // Ensure there are no dots in database name
  89. if (typeof databaseName === 'string' && databaseName.includes('.')) {
  90. throw new error_1.MongoInvalidArgumentError(`Database names cannot contain the character '.'`);
  91. }
  92. // Internal state of the db object
  93. this.s = {
  94. // Options
  95. 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: options?.pkFactory ?? 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. this.client = client;
  109. }
  110. get databaseName() {
  111. return this.s.namespace.db;
  112. }
  113. // Options
  114. get options() {
  115. return this.s.options;
  116. }
  117. /**
  118. * Check if a secondary can be used (because the read preference is *not* set to primary)
  119. */
  120. get secondaryOk() {
  121. return this.s.readPreference?.preference !== 'primary' || false;
  122. }
  123. get readConcern() {
  124. return this.s.readConcern;
  125. }
  126. /**
  127. * The current readPreference of the Db. If not explicitly defined for
  128. * this Db, will be inherited from the parent MongoClient
  129. */
  130. get readPreference() {
  131. if (this.s.readPreference == null) {
  132. return this.client.readPreference;
  133. }
  134. return this.s.readPreference;
  135. }
  136. get bsonOptions() {
  137. return this.s.bsonOptions;
  138. }
  139. // get the write Concern
  140. get writeConcern() {
  141. return this.s.writeConcern;
  142. }
  143. get namespace() {
  144. return this.s.namespace.toString();
  145. }
  146. get timeoutMS() {
  147. return this.s.options?.timeoutMS;
  148. }
  149. /**
  150. * Create a new collection on a server with the specified options. Use this to create capped collections.
  151. * More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/
  152. *
  153. * Collection namespace validation is performed server-side.
  154. *
  155. * @param name - The name of the collection to create
  156. * @param options - Optional settings for the command
  157. */
  158. async createCollection(name, options) {
  159. options = (0, utils_1.resolveOptions)(this, options);
  160. return await (0, create_collection_1.createCollections)(this, name, options);
  161. }
  162. /**
  163. * Execute a command
  164. *
  165. * @remarks
  166. * This command does not inherit options from the MongoClient.
  167. *
  168. * The driver will ensure the following fields are attached to the command sent to the server:
  169. * - `lsid` - sourced from an implicit session or options.session
  170. * - `$readPreference` - defaults to primary or can be configured by options.readPreference
  171. * - `$db` - sourced from the name of this database
  172. *
  173. * If the client has a serverApi setting:
  174. * - `apiVersion`
  175. * - `apiStrict`
  176. * - `apiDeprecationErrors`
  177. *
  178. * When in a transaction:
  179. * - `readConcern` - sourced from readConcern set on the TransactionOptions
  180. * - `writeConcern` - sourced from writeConcern set on the TransactionOptions
  181. *
  182. * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.
  183. *
  184. * @param command - The command to run
  185. * @param options - Optional settings for the command
  186. */
  187. async command(command, options) {
  188. // Intentionally, we do not inherit options from parent for this operation.
  189. return await (0, execute_operation_1.executeOperation)(this.client, new run_command_1.RunCommandOperation(this.s.namespace, command, (0, utils_1.resolveOptions)(undefined, {
  190. ...(0, bson_1.resolveBSONOptions)(options),
  191. timeoutMS: options?.timeoutMS ?? this.timeoutMS,
  192. session: options?.session,
  193. readPreference: options?.readPreference,
  194. signal: options?.signal
  195. })));
  196. }
  197. /**
  198. * Execute an aggregation framework pipeline against the database.
  199. *
  200. * @param pipeline - An array of aggregation stages to be executed
  201. * @param options - Optional settings for the command
  202. */
  203. aggregate(pipeline = [], options) {
  204. return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options));
  205. }
  206. /** Return the Admin db instance */
  207. admin() {
  208. return new admin_1.Admin(this);
  209. }
  210. /**
  211. * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.
  212. *
  213. * Collection namespace validation is performed server-side.
  214. *
  215. * @param name - the collection name we wish to access.
  216. * @returns return the new Collection instance
  217. */
  218. collection(name, options = {}) {
  219. if (typeof options === 'function') {
  220. throw new error_1.MongoInvalidArgumentError('The callback form of this helper has been removed.');
  221. }
  222. return new collection_1.Collection(this, name, (0, utils_1.resolveOptions)(this, options));
  223. }
  224. /**
  225. * Get all the db statistics.
  226. *
  227. * @param options - Optional settings for the command
  228. */
  229. async stats(options) {
  230. return await (0, execute_operation_1.executeOperation)(this.client, new stats_1.DbStatsOperation(this, (0, utils_1.resolveOptions)(this, options)));
  231. }
  232. listCollections(filter = {}, options = {}) {
  233. return new list_collections_cursor_1.ListCollectionsCursor(this, filter, (0, utils_1.resolveOptions)(this, options));
  234. }
  235. /**
  236. * Rename a collection.
  237. *
  238. * @remarks
  239. * This operation does not inherit options from the MongoClient.
  240. *
  241. * @param fromCollection - Name of current collection to rename
  242. * @param toCollection - New name of of the collection
  243. * @param options - Optional settings for the command
  244. */
  245. async renameCollection(fromCollection, toCollection, options) {
  246. // Intentionally, we do not inherit options from parent for this operation.
  247. return await (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this.collection(fromCollection), toCollection, (0, utils_1.resolveOptions)(undefined, {
  248. ...options,
  249. new_collection: true,
  250. readPreference: read_preference_1.ReadPreference.primary
  251. })));
  252. }
  253. /**
  254. * Drop a collection from the database, removing it permanently. New accesses will create a new collection.
  255. *
  256. * @param name - Name of collection to drop
  257. * @param options - Optional settings for the command
  258. */
  259. async dropCollection(name, options) {
  260. options = (0, utils_1.resolveOptions)(this, options);
  261. return await (0, drop_1.dropCollections)(this, name, options);
  262. }
  263. /**
  264. * Drop a database, removing it permanently from the server.
  265. *
  266. * @param options - Optional settings for the command
  267. */
  268. async dropDatabase(options) {
  269. return await (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropDatabaseOperation(this, (0, utils_1.resolveOptions)(this, options)));
  270. }
  271. /**
  272. * Fetch all collections for the current db.
  273. *
  274. * @param options - Optional settings for the command
  275. */
  276. async collections(options) {
  277. options = (0, utils_1.resolveOptions)(this, options);
  278. const collections = await this.listCollections({}, { ...options, nameOnly: true }).toArray();
  279. return collections
  280. .filter(
  281. // Filter collections removing any illegal ones
  282. ({ name }) => !name.includes('$'))
  283. .map(({ name }) => new collection_1.Collection(this, name, this.s.options));
  284. }
  285. /**
  286. * Creates an index on the db and collection.
  287. *
  288. * @param name - Name of the collection to create the index on.
  289. * @param indexSpec - Specify the field to index, or an index specification
  290. * @param options - Optional settings for the command
  291. */
  292. async createIndex(name, indexSpec, options) {
  293. const indexes = await (0, execute_operation_1.executeOperation)(this.client, indexes_1.CreateIndexesOperation.fromIndexSpecification(this, name, indexSpec, options));
  294. return indexes[0];
  295. }
  296. /**
  297. * Remove a user from a database
  298. *
  299. * @param username - The username to remove
  300. * @param options - Optional settings for the command
  301. */
  302. async removeUser(username, options) {
  303. return await (0, execute_operation_1.executeOperation)(this.client, new remove_user_1.RemoveUserOperation(this, username, (0, utils_1.resolveOptions)(this, options)));
  304. }
  305. /**
  306. * Set the current profiling level of MongoDB
  307. *
  308. * @param level - The new profiling level (off, slow_only, all).
  309. * @param options - Optional settings for the command
  310. */
  311. async setProfilingLevel(level, options) {
  312. return await (0, execute_operation_1.executeOperation)(this.client, new set_profiling_level_1.SetProfilingLevelOperation(this, level, (0, utils_1.resolveOptions)(this, options)));
  313. }
  314. /**
  315. * Retrieve the current profiling Level for MongoDB
  316. *
  317. * @param options - Optional settings for the command
  318. */
  319. async profilingLevel(options) {
  320. return await (0, execute_operation_1.executeOperation)(this.client, new profiling_level_1.ProfilingLevelOperation(this, (0, utils_1.resolveOptions)(this, options)));
  321. }
  322. async indexInformation(name, options) {
  323. return await this.collection(name).indexInformation((0, utils_1.resolveOptions)(this, options));
  324. }
  325. /**
  326. * Create a new Change Stream, watching for new changes (insertions, updates,
  327. * replacements, deletions, and invalidations) in this database. Will ignore all
  328. * changes to system collections.
  329. *
  330. * @remarks
  331. * watch() accepts two generic arguments for distinct use cases:
  332. * - The first is to provide the schema that may be defined for all the collections within this database
  333. * - 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
  334. *
  335. * @remarks
  336. * When `timeoutMS` is configured for a change stream, it will have different behaviour depending
  337. * on whether the change stream is in iterator mode or emitter mode. In both cases, a change
  338. * stream will time out if it does not receive a change event within `timeoutMS` of the last change
  339. * event.
  340. *
  341. * Note that if a change stream is consistently timing out when watching a collection, database or
  342. * client that is being changed, then this may be due to the server timing out before it can finish
  343. * processing the existing oplog. To address this, restart the change stream with a higher
  344. * `timeoutMS`.
  345. *
  346. * If the change stream times out the initial aggregate operation to establish the change stream on
  347. * the server, then the client will close the change stream. If the getMore calls to the server
  348. * time out, then the change stream will be left open, but will throw a MongoOperationTimeoutError
  349. * when in iterator mode and emit an error event that returns a MongoOperationTimeoutError in
  350. * emitter mode.
  351. *
  352. * To determine whether or not the change stream is still open following a timeout, check the
  353. * {@link ChangeStream.closed} getter.
  354. *
  355. * @example
  356. * In iterator mode, if a next() call throws a timeout error, it will attempt to resume the change stream.
  357. * The next call can just be retried after this succeeds.
  358. * ```ts
  359. * const changeStream = collection.watch([], { timeoutMS: 100 });
  360. * try {
  361. * await changeStream.next();
  362. * } catch (e) {
  363. * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
  364. * await changeStream.next();
  365. * }
  366. * throw e;
  367. * }
  368. * ```
  369. *
  370. * @example
  371. * In emitter mode, if the change stream goes `timeoutMS` without emitting a change event, it will
  372. * emit an error event that returns a MongoOperationTimeoutError, but will not close the change
  373. * stream unless the resume attempt fails. There is no need to re-establish change listeners as
  374. * this will automatically continue emitting change events once the resume attempt completes.
  375. *
  376. * ```ts
  377. * const changeStream = collection.watch([], { timeoutMS: 100 });
  378. * changeStream.on('change', console.log);
  379. * changeStream.on('error', e => {
  380. * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
  381. * // do nothing
  382. * } else {
  383. * changeStream.close();
  384. * }
  385. * });
  386. * ```
  387. * @param pipeline - An array of {@link https://www.mongodb.com/docs/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.
  388. * @param options - Optional settings for the command
  389. * @typeParam TSchema - Type of the data being detected by the change stream
  390. * @typeParam TChange - Type of the whole change stream document emitted
  391. */
  392. watch(pipeline = [], options = {}) {
  393. // Allow optionally not specifying a pipeline
  394. if (!Array.isArray(pipeline)) {
  395. options = pipeline;
  396. pipeline = [];
  397. }
  398. return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options));
  399. }
  400. /**
  401. * A low level cursor API providing basic driver functionality:
  402. * - ClientSession management
  403. * - ReadPreference for server selection
  404. * - Running getMores automatically when a local batch is exhausted
  405. *
  406. * @param command - The command that will start a cursor on the server.
  407. * @param options - Configurations for running the command, bson options will apply to getMores
  408. */
  409. runCursorCommand(command, options) {
  410. return new run_command_cursor_1.RunCommandCursor(this, command, options);
  411. }
  412. }
  413. exports.Db = Db;
  414. Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION;
  415. Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION;
  416. Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION;
  417. Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION;
  418. Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION;
  419. Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION;
  420. //# sourceMappingURL=db.js.map