PageRenderTime 50ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/node_modules/mongodb/README.md

https://gitlab.com/jeenjacob/weTwee
Markdown | 279 lines | 189 code | 90 blank | 0 comment | 0 complexity | 3425d32da432f5af4d0f22bd8e522e8e MD5 | raw file
  1. # MongoDB NodeJS Driver
  2. The official [MongoDB](https://www.mongodb.com/) driver for Node.js.
  3. **Upgrading to version 4? Take a look at our [upgrade guide here](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_4.0.0.md)!**
  4. ## Quick Links
  5. | what | where |
  6. | ------------- | ------------------------------------------------------------------------------------------------------- |
  7. | documentation | [docs.mongodb.com/drivers/node](https://docs.mongodb.com/drivers/node) |
  8. | api-doc | [mongodb.github.io/node-mongodb-native/](https://mongodb.github.io/node-mongodb-native/) |
  9. | npm package | [www.npmjs.com/package/mongodb](https://www.npmjs.com/package/mongodb) |
  10. | source | [github.com/mongodb/node-mongodb-native](https://github.com/mongodb/node-mongodb-native) |
  11. | mongodb | [www.mongodb.com](https://www.mongodb.com) |
  12. | changelog | [HISTORY.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/HISTORY.md) |
  13. | upgrade to v4 | [etc/notes/CHANGES_4.0.0.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_4.0.0.md) |
  14. | contributing | [CONTRIBUTING.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/CONTRIBUTING.md) |
  15. ### Bugs / Feature Requests
  16. Think youve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a
  17. case in our issue management tool, JIRA:
  18. - Create an account and login [jira.mongodb.org](https://jira.mongodb.org).
  19. - Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE).
  20. - Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it.
  21. Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the
  22. Core Server (i.e. SERVER) project are **public**.
  23. ### Support / Feedback
  24. For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](https://docs.mongodb.com/manual/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [MongoDB Community Forums](https://community.mongodb.com/tags/c/drivers-odms-connectors/7/node-js-driver).
  25. ### Change Log
  26. Change history can be found in [`HISTORY.md`](https://github.com/mongodb/node-mongodb-native/blob/HEAD/HISTORY.md).
  27. ### Compatibility
  28. For version compatibility matrices, please refer to the following links:
  29. - [MongoDB](https://docs.mongodb.com/drivers/node/current/compatibility/#mongodb-compatibility)
  30. - [NodeJS](https://docs.mongodb.com/drivers/node/current/compatibility/#language-compatibility)
  31. #### Typescript Version
  32. We recommend using the latest version of typescript, however we do provide a [downleveled](https://github.com/sandersn/downlevel-dts#readme) version of the type definitions that we test compiling against `typescript@4.1.6`.
  33. Since typescript [does not restrict breaking changes to major versions](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes) we consider this support best effort.
  34. If you run into any unexpected compiler failures please let us know and we will do our best to correct it.
  35. ## Installation
  36. The recommended way to get started using the Node.js 4.x driver is by using the `npm` (Node Package Manager) to install the dependency in your project.
  37. After you've created your own project using `npm init`, you can run:
  38. ```bash
  39. npm install mongodb
  40. # or ...
  41. yarn add mongodb
  42. ```
  43. This will download the MongoDB driver and add a dependency entry in your `package.json` file.
  44. If you are a Typescript user, you will need the Node.js type definitions to use the driver's definitions:
  45. ```sh
  46. npm install -D @types/node
  47. ```
  48. ## Troubleshooting
  49. The MongoDB driver depends on several other packages. These are:
  50. - [bson](https://github.com/mongodb/js-bson)
  51. - [bson-ext](https://github.com/mongodb-js/bson-ext)
  52. - [kerberos](https://github.com/mongodb-js/kerberos)
  53. - [mongodb-client-encryption](https://github.com/mongodb/libmongocrypt#readme)
  54. Some of these packages include native C++ extensions. Consult the [trouble shooting guide here](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/native-extensions.md) if you run into issues.
  55. ## Quick Start
  56. This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [official documentation](https://docs.mongodb.com/drivers/node/).
  57. ### Create the `package.json` file
  58. First, create a directory where your application will live.
  59. ```bash
  60. mkdir myProject
  61. cd myProject
  62. ```
  63. Enter the following command and answer the questions to create the initial structure for your new project:
  64. ```bash
  65. npm init -y
  66. ```
  67. Next, install the driver as a dependency.
  68. ```bash
  69. npm install mongodb
  70. ```
  71. ### Start a MongoDB Server
  72. For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/).
  73. 1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads)
  74. 2. Create a database directory (in this case under **/data**).
  75. 3. Install and start a `mongod` process.
  76. ```bash
  77. mongod --dbpath=/data
  78. ```
  79. You should see the **mongod** process start up and print some status information.
  80. ### Connect to MongoDB
  81. Create a new **app.js** file and add the following code to try out some basic CRUD
  82. operations using the MongoDB driver.
  83. Add code to connect to the server and the database **myProject**:
  84. > **NOTE:** All the examples below use async/await syntax.
  85. >
  86. > However, all async API calls support an optional callback as the final argument,
  87. > if a callback is provided a Promise will not be returned.
  88. ```js
  89. const { MongoClient } = require('mongodb');
  90. // or as an es module:
  91. // import { MongoClient } from 'mongodb'
  92. // Connection URL
  93. const url = 'mongodb://localhost:27017';
  94. const client = new MongoClient(url);
  95. // Database Name
  96. const dbName = 'myProject';
  97. async function main() {
  98. // Use connect method to connect to the server
  99. await client.connect();
  100. console.log('Connected successfully to server');
  101. const db = client.db(dbName);
  102. const collection = db.collection('documents');
  103. // the following code examples can be pasted here...
  104. return 'done.';
  105. }
  106. main()
  107. .then(console.log)
  108. .catch(console.error)
  109. .finally(() => client.close());
  110. ```
  111. Run your app from the command line with:
  112. ```bash
  113. node app.js
  114. ```
  115. The application should print **Connected successfully to server** to the console.
  116. ### Insert a Document
  117. Add to **app.js** the following function which uses the **insertMany**
  118. method to add three documents to the **documents** collection.
  119. ```js
  120. const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]);
  121. console.log('Inserted documents =>', insertResult);
  122. ```
  123. The **insertMany** command returns an object with information about the insert operations.
  124. ### Find All Documents
  125. Add a query that returns all the documents.
  126. ```js
  127. const findResult = await collection.find({}).toArray();
  128. console.log('Found documents =>', findResult);
  129. ```
  130. This query returns all the documents in the **documents** collection.
  131. If you add this below the insertMany example you'll see the document's you've inserted.
  132. ### Find Documents with a Query Filter
  133. Add a query filter to find only documents which meet the query criteria.
  134. ```js
  135. const filteredDocs = await collection.find({ a: 3 }).toArray();
  136. console.log('Found documents filtered by { a: 3 } =>', filteredDocs);
  137. ```
  138. Only the documents which match `'a' : 3` should be returned.
  139. ### Update a document
  140. The following operation updates a document in the **documents** collection.
  141. ```js
  142. const updateResult = await collection.updateOne({ a: 3 }, { $set: { b: 1 } });
  143. console.log('Updated documents =>', updateResult);
  144. ```
  145. The method updates the first document where the field **a** is equal to **3** by adding a new field **b** to the document set to **1**. `updateResult` contains information about whether there was a matching document to update or not.
  146. ### Remove a document
  147. Remove the document where the field **a** is equal to **3**.
  148. ```js
  149. const deleteResult = await collection.deleteMany({ a: 3 });
  150. console.log('Deleted documents =>', deleteResult);
  151. ```
  152. ### Index a Collection
  153. [Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's
  154. performance. The following function creates an index on the **a** field in the
  155. **documents** collection.
  156. ```js
  157. const indexName = await collection.createIndex({ a: 1 });
  158. console.log('index name =', indexName);
  159. ```
  160. For more detailed information, see the [indexing strategies page](https://docs.mongodb.com/manual/applications/indexes/).
  161. ## Error Handling
  162. If you need to filter certain errors from our driver we have a helpful tree of errors described in [etc/notes/errors.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/errors.md).
  163. It is our recommendation to use `instanceof` checks on errors and to avoid relying on parsing `error.message` and `error.name` strings in your code.
  164. We guarantee `instanceof` checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors.
  165. Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release.
  166. This means `instanceof` will always be able to accurately capture the errors that our driver throws (or returns in a callback).
  167. ```typescript
  168. const client = new MongoClient(url);
  169. await client.connect();
  170. const collection = client.db().collection('collection');
  171. try {
  172. await collection.insertOne({ _id: 1 });
  173. await collection.insertOne({ _id: 1 }); // duplicate key error
  174. } catch (error) {
  175. if (error instanceof MongoServerError) {
  176. console.log(`Error worth logging: ${error}`); // special case for some reason
  177. }
  178. throw error; // still want to crash
  179. }
  180. ```
  181. ## Next Steps
  182. - [MongoDB Documentation](https://docs.mongodb.com/manual/)
  183. - [MongoDB Node Driver Documentation](https://docs.mongodb.com/drivers/node/)
  184. - [Read about Schemas](https://docs.mongodb.com/manual/core/data-modeling-introduction/)
  185. - [Star us on GitHub](https://github.com/mongodb/node-mongodb-native)
  186. ## License
  187. [Apache 2.0](LICENSE.md)
  188. © 2009-2012 Christian Amor Kvalheim
  189. © 2012-present MongoDB [Contributors](https://github.com/mongodb/node-mongodb-native/blob/HEAD/CONTRIBUTORS.md)