Skip to content

Commit 3cafc09

Browse files
authored
docs(NODE-3569): describe the error API based on instanceof check (#2948)
1 parent 1c576e9 commit 3cafc09

File tree

3 files changed

+73
-50
lines changed

3 files changed

+73
-50
lines changed

README.md

Lines changed: 51 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
The official [MongoDB](https://www.mongodb.com/) driver for Node.js.
44

5-
**Upgrading to version 4? Take a look at our [upgrade guide here](https://github.com/mongodb/node-mongodb-native/blob/4.0/docs/CHANGES_4.0.0.md)!**
5+
**Upgrading to version 4? Take a look at our [upgrade guide here](https://github.com/mongodb/node-mongodb-native/blob/4.1/docs/CHANGES_4.0.0.md)!**
66

77
## Quick Links
88

@@ -72,7 +72,7 @@ The MongoDB driver depends on several other packages. These are:
7272
- [kerberos](https://github.com/mongodb-js/kerberos)
7373
- [mongodb-client-encryption](https://github.com/mongodb/libmongocrypt#readme)
7474

75-
Some of these packages include native C++ extensions, consult the [trouble shooting guide here](https://github.com/mongodb/node-mongodb-native/blob/4.0/docs/native-extensions.md) if you run into issues.
75+
Some of these packages include native C++ extensions, consult the [trouble shooting guide here](https://github.com/mongodb/node-mongodb-native/blob/4.1/docs/native-extensions.md) if you run into issues.
7676

7777
## Quick Start
7878

@@ -126,33 +126,33 @@ Add code to connect to the server and the database **myProject**:
126126
> if a callback is provided a Promise will not be returned.
127127
128128
```js
129-
const { MongoClient } = require('mongodb')
129+
const { MongoClient } = require('mongodb');
130130
// or as an es module:
131131
// import { MongoClient } from 'mongodb'
132132

133133
// Connection URL
134-
const url = 'mongodb://localhost:27017'
135-
const client = new MongoClient(url)
134+
const url = 'mongodb://localhost:27017';
135+
const client = new MongoClient(url);
136136

137137
// Database Name
138-
const dbName = 'myProject'
138+
const dbName = 'myProject';
139139

140140
async function main() {
141141
// Use connect method to connect to the server
142-
await client.connect()
143-
console.log('Connected successfully to server')
144-
const db = client.db(dbName)
145-
const collection = db.collection('documents')
142+
await client.connect();
143+
console.log('Connected successfully to server');
144+
const db = client.db(dbName);
145+
const collection = db.collection('documents');
146146

147147
// the following code examples can be pasted here...
148148

149-
return 'done.'
149+
return 'done.';
150150
}
151151

152152
main()
153153
.then(console.log)
154154
.catch(console.error)
155-
.finally(() => client.close())
155+
.finally(() => client.close());
156156
```
157157

158158
Run your app from the command line with:
@@ -169,8 +169,8 @@ Add to **app.js** the following function which uses the **insertMany**
169169
method to add three documents to the **documents** collection.
170170

171171
```js
172-
const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }])
173-
console.log('Inserted documents =>', insertResult)
172+
const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]);
173+
console.log('Inserted documents =>', insertResult);
174174
```
175175

176176
The **insertMany** command returns an object with information about the insert operations.
@@ -180,8 +180,8 @@ The **insertMany** command returns an object with information about the insert o
180180
Add a query that returns all the documents.
181181

182182
```js
183-
const findResult = await collection.find({}).toArray()
184-
console.log('Found documents =>', findResult)
183+
const findResult = await collection.find({}).toArray();
184+
console.log('Found documents =>', findResult);
185185
```
186186

187187
This query returns all the documents in the **documents** collection.
@@ -192,8 +192,8 @@ If you add this below the insertMany example you'll see the document's you've in
192192
Add a query filter to find only documents which meet the query criteria.
193193

194194
```js
195-
const filteredDocs = await collection.find({ a: 3 }).toArray()
196-
console.log('Found documents filtered by { a: 3 } =>', filteredDocs)
195+
const filteredDocs = await collection.find({ a: 3 }).toArray();
196+
console.log('Found documents filtered by { a: 3 } =>', filteredDocs);
197197
```
198198

199199
Only the documents which match `'a' : 3` should be returned.
@@ -203,8 +203,8 @@ Only the documents which match `'a' : 3` should be returned.
203203
The following operation updates a document in the **documents** collection.
204204

205205
```js
206-
const updateResult = await collection.updateOne({ a: 3 }, { $set: { b: 1 } })
207-
console.log('Updated documents =>', updateResult)
206+
const updateResult = await collection.updateOne({ a: 3 }, { $set: { b: 1 } });
207+
console.log('Updated documents =>', updateResult);
208208
```
209209

210210
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.
@@ -214,8 +214,8 @@ The method updates the first document where the field **a** is equal to **3** by
214214
Remove the document where the field **a** is equal to **3**.
215215

216216
```js
217-
const deleteResult = await collection.deleteMany({ a: 3 })
218-
console.log('Deleted documents =>', deleteResult)
217+
const deleteResult = await collection.deleteMany({ a: 3 });
218+
console.log('Deleted documents =>', deleteResult);
219219
```
220220

221221
### Index a Collection
@@ -225,12 +225,38 @@ performance. The following function creates an index on the **a** field in the
225225
**documents** collection.
226226

227227
```js
228-
const indexName = await collection.createIndex({ a: 1 })
229-
console.log('index name =', indexName)
228+
const indexName = await collection.createIndex({ a: 1 });
229+
console.log('index name =', indexName);
230230
```
231231

232232
For more detailed information, see the [indexing strategies page](https://docs.mongodb.com/manual/applications/indexes/).
233233

234+
## Error Handling
235+
236+
If you need to filter certain errors from our driver we have a helpful tree of errors described in [docs/errors.md](https://github.com/mongodb/node-mongodb-native/blob/4.1/docs/errors.md).
237+
238+
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.
239+
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.
240+
241+
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.
242+
This means `instanceof` will always be able to accurately capture the errors that our driver throws (or returns in a callback).
243+
244+
```typescript
245+
const client = new MongoClient(url);
246+
await client.connect();
247+
const collection = client.db().collection('collection');
248+
249+
try {
250+
await collection.insertOne({ _id: 1 });
251+
await collection.insertOne({ _id: 1 }); // duplicate key error
252+
} catch (error) {
253+
if (error instanceof MongoServerError) {
254+
console.log(`Error worth logging: ${error}`); // special case for some reason
255+
}
256+
throw error; // still want to crash
257+
}
258+
```
259+
234260
## Next Steps
235261

236262
- [MongoDB Documentation](https://docs.mongodb.com/manual/)
@@ -243,4 +269,4 @@ For more detailed information, see the [indexing strategies page](https://docs.m
243269
[Apache 2.0](LICENSE.md)
244270

245271
© 2009-2012 Christian Amor Kvalheim
246-
© 2012-present MongoDB [Contributors](https://github.com/mongodb/node-mongodb-native/blob/4.0/CONTRIBUTORS.md)
272+
© 2012-present MongoDB [Contributors](https://github.com/mongodb/node-mongodb-native/blob/4.1/CONTRIBUTORS.md)

package-lock.json

Lines changed: 21 additions & 24 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
"email": "[email protected]"
3333
},
3434
"dependencies": {
35-
"bson": "^4.5.0",
35+
"bson": "^4.5.1",
3636
"denque": "^1.5.0",
3737
"mongodb-connection-string-url": "^2.0.0"
3838
},

0 commit comments

Comments
 (0)