db.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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 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 profiling_level_1 = require("./operations/profiling_level");
  19. const remove_user_1 = require("./operations/remove_user");
  20. const rename_1 = require("./operations/rename");
  21. const run_command_1 = require("./operations/run_command");
  22. const set_profiling_level_1 = require("./operations/set_profiling_level");
  23. const stats_1 = require("./operations/stats");
  24. const read_concern_1 = require("./read_concern");
  25. const read_preference_1 = require("./read_preference");
  26. const utils_1 = require("./utils");
  27. const write_concern_1 = require("./write_concern");
  28. // Allowed parameters
  29. const DB_OPTIONS_ALLOW_LIST = [
  30. 'writeConcern',
  31. 'readPreference',
  32. 'readPreferenceTags',
  33. 'native_parser',
  34. 'forceServerObjectId',
  35. 'pkFactory',
  36. 'serializeFunctions',
  37. 'raw',
  38. 'authSource',
  39. 'ignoreUndefined',
  40. 'readConcern',
  41. 'retryMiliSeconds',
  42. 'numberOfRetries',
  43. 'useBigInt64',
  44. 'promoteBuffers',
  45. 'promoteLongs',
  46. 'bsonRegExp',
  47. 'enableUtf8Validation',
  48. 'promoteValues',
  49. 'compression',
  50. 'retryWrites'
  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. /**
  147. * Create a new collection on a server with the specified options. Use this to create capped collections.
  148. * More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/
  149. *
  150. * Collection namespace validation is performed server-side.
  151. *
  152. * @param name - The name of the collection to create
  153. * @param options - Optional settings for the command
  154. */
  155. async createCollection(name, options) {
  156. return (0, execute_operation_1.executeOperation)(this.client, new create_collection_1.CreateCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)));
  157. }
  158. /**
  159. * Execute a command
  160. *
  161. * @remarks
  162. * This command does not inherit options from the MongoClient.
  163. *
  164. * The driver will ensure the following fields are attached to the command sent to the server:
  165. * - `lsid` - sourced from an implicit session or options.session
  166. * - `$readPreference` - defaults to primary or can be configured by options.readPreference
  167. * - `$db` - sourced from the name of this database
  168. *
  169. * If the client has a serverApi setting:
  170. * - `apiVersion`
  171. * - `apiStrict`
  172. * - `apiDeprecationErrors`
  173. *
  174. * When in a transaction:
  175. * - `readConcern` - sourced from readConcern set on the TransactionOptions
  176. * - `writeConcern` - sourced from writeConcern set on the TransactionOptions
  177. *
  178. * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.
  179. *
  180. * @param command - The command to run
  181. * @param options - Optional settings for the command
  182. */
  183. async command(command, options) {
  184. // Intentionally, we do not inherit options from parent for this operation.
  185. return (0, execute_operation_1.executeOperation)(this.client, new run_command_1.RunCommandOperation(this, command, {
  186. ...(0, bson_1.resolveBSONOptions)(options),
  187. session: options?.session,
  188. readPreference: options?.readPreference
  189. }));
  190. }
  191. /**
  192. * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6
  193. *
  194. * @param pipeline - An array of aggregation stages to be executed
  195. * @param options - Optional settings for the command
  196. */
  197. aggregate(pipeline = [], options) {
  198. return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options));
  199. }
  200. /** Return the Admin db instance */
  201. admin() {
  202. return new admin_1.Admin(this);
  203. }
  204. /**
  205. * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.
  206. *
  207. * Collection namespace validation is performed server-side.
  208. *
  209. * @param name - the collection name we wish to access.
  210. * @returns return the new Collection instance
  211. */
  212. collection(name, options = {}) {
  213. if (typeof options === 'function') {
  214. throw new error_1.MongoInvalidArgumentError('The callback form of this helper has been removed.');
  215. }
  216. return new collection_1.Collection(this, name, (0, utils_1.resolveOptions)(this, options));
  217. }
  218. /**
  219. * Get all the db statistics.
  220. *
  221. * @param options - Optional settings for the command
  222. */
  223. async stats(options) {
  224. return (0, execute_operation_1.executeOperation)(this.client, new stats_1.DbStatsOperation(this, (0, utils_1.resolveOptions)(this, options)));
  225. }
  226. listCollections(filter = {}, options = {}) {
  227. return new list_collections_cursor_1.ListCollectionsCursor(this, filter, (0, utils_1.resolveOptions)(this, options));
  228. }
  229. /**
  230. * Rename a collection.
  231. *
  232. * @remarks
  233. * This operation does not inherit options from the MongoClient.
  234. *
  235. * @param fromCollection - Name of current collection to rename
  236. * @param toCollection - New name of of the collection
  237. * @param options - Optional settings for the command
  238. */
  239. async renameCollection(fromCollection, toCollection, options) {
  240. // Intentionally, we do not inherit options from parent for this operation.
  241. return (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this.collection(fromCollection), toCollection, { ...options, new_collection: true, readPreference: read_preference_1.ReadPreference.primary }));
  242. }
  243. /**
  244. * Drop a collection from the database, removing it permanently. New accesses will create a new collection.
  245. *
  246. * @param name - Name of collection to drop
  247. * @param options - Optional settings for the command
  248. */
  249. async dropCollection(name, options) {
  250. return (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)));
  251. }
  252. /**
  253. * Drop a database, removing it permanently from the server.
  254. *
  255. * @param options - Optional settings for the command
  256. */
  257. async dropDatabase(options) {
  258. return (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropDatabaseOperation(this, (0, utils_1.resolveOptions)(this, options)));
  259. }
  260. /**
  261. * Fetch all collections for the current db.
  262. *
  263. * @param options - Optional settings for the command
  264. */
  265. async collections(options) {
  266. return (0, execute_operation_1.executeOperation)(this.client, new collections_1.CollectionsOperation(this, (0, utils_1.resolveOptions)(this, options)));
  267. }
  268. /**
  269. * Creates an index on the db and collection.
  270. *
  271. * @param name - Name of the collection to create the index on.
  272. * @param indexSpec - Specify the field to index, or an index specification
  273. * @param options - Optional settings for the command
  274. */
  275. async createIndex(name, indexSpec, options) {
  276. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.CreateIndexOperation(this, name, indexSpec, (0, utils_1.resolveOptions)(this, options)));
  277. }
  278. /**
  279. * Remove a user from a database
  280. *
  281. * @param username - The username to remove
  282. * @param options - Optional settings for the command
  283. */
  284. async removeUser(username, options) {
  285. return (0, execute_operation_1.executeOperation)(this.client, new remove_user_1.RemoveUserOperation(this, username, (0, utils_1.resolveOptions)(this, options)));
  286. }
  287. /**
  288. * Set the current profiling level of MongoDB
  289. *
  290. * @param level - The new profiling level (off, slow_only, all).
  291. * @param options - Optional settings for the command
  292. */
  293. async setProfilingLevel(level, options) {
  294. return (0, execute_operation_1.executeOperation)(this.client, new set_profiling_level_1.SetProfilingLevelOperation(this, level, (0, utils_1.resolveOptions)(this, options)));
  295. }
  296. /**
  297. * Retrieve the current profiling Level for MongoDB
  298. *
  299. * @param options - Optional settings for the command
  300. */
  301. async profilingLevel(options) {
  302. return (0, execute_operation_1.executeOperation)(this.client, new profiling_level_1.ProfilingLevelOperation(this, (0, utils_1.resolveOptions)(this, options)));
  303. }
  304. /**
  305. * Retrieves this collections index info.
  306. *
  307. * @param name - The name of the collection.
  308. * @param options - Optional settings for the command
  309. */
  310. async indexInformation(name, options) {
  311. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexInformationOperation(this, name, (0, utils_1.resolveOptions)(this, options)));
  312. }
  313. /**
  314. * Create a new Change Stream, watching for new changes (insertions, updates,
  315. * replacements, deletions, and invalidations) in this database. Will ignore all
  316. * changes to system collections.
  317. *
  318. * @remarks
  319. * watch() accepts two generic arguments for distinct use cases:
  320. * - The first is to provide the schema that may be defined for all the collections within this database
  321. * - 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
  322. *
  323. * @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.
  324. * @param options - Optional settings for the command
  325. * @typeParam TSchema - Type of the data being detected by the change stream
  326. * @typeParam TChange - Type of the whole change stream document emitted
  327. */
  328. watch(pipeline = [], options = {}) {
  329. // Allow optionally not specifying a pipeline
  330. if (!Array.isArray(pipeline)) {
  331. options = pipeline;
  332. pipeline = [];
  333. }
  334. return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options));
  335. }
  336. /**
  337. * A low level cursor API providing basic driver functionality:
  338. * - ClientSession management
  339. * - ReadPreference for server selection
  340. * - Running getMores automatically when a local batch is exhausted
  341. *
  342. * @param command - The command that will start a cursor on the server.
  343. * @param options - Configurations for running the command, bson options will apply to getMores
  344. */
  345. runCursorCommand(command, options) {
  346. return new run_command_cursor_1.RunCommandCursor(this, command, options);
  347. }
  348. }
  349. Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION;
  350. Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION;
  351. Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION;
  352. Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION;
  353. Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION;
  354. Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION;
  355. exports.Db = Db;
  356. //# sourceMappingURL=db.js.map