├── LICENSE ├── README.md ├── aggregation.js ├── changeStreams.js ├── changeStreamsTestData.js ├── connection.js ├── create.js ├── delete.js ├── read.js ├── template.js ├── transaction-bankingexample.js ├── transaction-inventoryexample.js ├── transaction.js ├── update.js └── usersCollection.js /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2021 MongoDB Inc. 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Quick Start: Node.js and MongoDB 2 | 3 | This repository will walk you through the process of quickly getting started using Node.js and MongoDB together. 4 | 5 | This branch uses MongoDB 4.4, MongoDB Node.js Driver 3.6.4, and Node.js 14.15.4. To see an earlier version that uses MongoDB 4.0, MongoDB Node.js Driver 3.3.2, and Node.js 10.16.3, visit the [3.3.2 branch](https://github.com/mongodb-developer/nodejs-quickstart/tree/3.3.2). 6 | 7 | ## Topics 8 | 9 | * How to get connected to your database: [blog post](https://developer.mongodb.com/quickstart/node-connect-mongodb/) | [code example](connection.js) 10 | * Creating documents: [blog post](https://developer.mongodb.com/quickstart/node-crud-tutorial/) | [code example](create.js) 11 | * Reading documents: [blog post](https://developer.mongodb.com/quickstart/node-crud-tutorial/) | [code example](read.js) 12 | * Updating documents: [blog post](https://developer.mongodb.com/quickstart/node-crud-tutorial/) | [code example](update.js) 13 | * Deleting documents: [blog post](https://developer.mongodb.com/quickstart/node-crud-tutorial/) | [code example](delete.js) 14 | * The aggregation framework: [blog post](https://developer.mongodb.com/quickstart/node-aggregation-framework/) | [code example](aggregation.js) 15 | * Transactions: [blog post](https://developer.mongodb.com/quickstart/node-transactions/) | [code example](transaction.js) 16 | * Change streams: [blog post](https://developer.mongodb.com/quickstart/nodejs-change-streams-triggers/) | [code example](changeStreams.js) 17 | 18 | ## Related Videos 19 | 20 | [How to Perform the CRUD Operations Using MongoDB & Node.js](https://youtu.be/ayNI9Q84v8g) 21 | 22 | ## Questions? 23 | 24 | Questions about this repo or how to use MongoDB and Node.js together? Ask them in the [MongoDB Community](https://community.mongodb.com). 25 | -------------------------------------------------------------------------------- /aggregation.js: -------------------------------------------------------------------------------- 1 | const { MongoClient } = require('mongodb'); 2 | 3 | async function main() { 4 | /** 5 | * Connection URI. Update , , and to reflect your cluster. 6 | * See https://docs.mongodb.com/drivers/node/ for more details 7 | */ 8 | const uri = "mongodb+srv://:@/sample_airbnb?retryWrites=true&w=majority"; 9 | 10 | /** 11 | * The Mongo Client you will use to interact with your database 12 | * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details 13 | * In case: '[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated...' 14 | * pass option { useUnifiedTopology: true } to the MongoClient constructor. 15 | * const client = new MongoClient(uri, {useUnifiedTopology: true}) 16 | */ 17 | const client = new MongoClient(uri); 18 | 19 | try { 20 | // Connect to the MongoDB cluster 21 | await client.connect(); 22 | 23 | // Make the appropriate DB calls 24 | 25 | // Print the 10 cheapest suburbs in the Sydney, Australia market 26 | await printCheapestSuburbs(client, "Australia", "Sydney", 10); 27 | 28 | } finally { 29 | // Close the connection to the MongoDB cluster 30 | await client.close(); 31 | } 32 | } 33 | 34 | main().catch(console.error); 35 | 36 | /** 37 | * Print the cheapest suburbs for a given market 38 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 39 | * @param {String} country The country for the given market 40 | * @param {String} market The market you want to search 41 | * @param {number} maxNumberToPrint The maximum number of suburbs to print 42 | */ 43 | async function printCheapestSuburbs(client, country, market, maxNumberToPrint) { 44 | const pipeline = [ 45 | { 46 | '$match': { 47 | 'bedrooms': 1, 48 | 'address.country': country, 49 | 'address.market': market, 50 | 'address.suburb': { 51 | '$exists': 1, 52 | '$ne': '' 53 | }, 54 | 'room_type': 'Entire home/apt' 55 | } 56 | }, { 57 | '$group': { 58 | '_id': '$address.suburb', 59 | 'averagePrice': { 60 | '$avg': '$price' 61 | } 62 | } 63 | }, { 64 | '$sort': { 65 | 'averagePrice': 1 66 | } 67 | }, { 68 | '$limit': maxNumberToPrint 69 | } 70 | ]; 71 | 72 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#aggregate for the aggregate() docs 73 | const aggCursor = client.db("sample_airbnb").collection("listingsAndReviews").aggregate(pipeline); 74 | 75 | await aggCursor.forEach(airbnbListing => { 76 | console.log(`${airbnbListing._id}: ${airbnbListing.averagePrice}`); 77 | }); 78 | } 79 | -------------------------------------------------------------------------------- /changeStreams.js: -------------------------------------------------------------------------------- 1 | const { MongoClient } = require('mongodb'); 2 | const stream = require('stream'); 3 | 4 | async function main() { 5 | /** 6 | * Connection URI. Update , , and to reflect your cluster. 7 | * See https://docs.mongodb.com/drivers/node/ for more details 8 | */ 9 | const uri = "mongodb+srv://:@/sample_airbnb?retryWrites=true&w=majority"; 10 | 11 | /** 12 | * The Mongo Client you will use to interact with your database 13 | * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details 14 | * In case: '[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated...' 15 | * pass option { useUnifiedTopology: true } to the MongoClient constructor. 16 | * const client = new MongoClient(uri, {useUnifiedTopology: true}) 17 | */ 18 | const client = new MongoClient(uri); 19 | 20 | try { 21 | // Connect to the MongoDB cluster 22 | await client.connect(); 23 | 24 | // Make the appropriate DB calls 25 | 26 | /** 27 | * An aggregation pipeline that matches on new listings in the country of Australia and the Sydney market 28 | */ 29 | const pipeline = [ 30 | { 31 | '$match': { 32 | 'operationType': 'insert', 33 | 'fullDocument.address.country': 'Australia', 34 | 'fullDocument.address.market': 'Sydney' 35 | } 36 | } 37 | ]; 38 | 39 | // This script contains three ways to monitor new listings in the listingsAndReviews collection. 40 | // Comment in the monitoring function you'd like to use. 41 | 42 | // OPTION ONE: Monitor new listings using EventEmitter's on() function. 43 | // await monitorListingsUsingEventEmitter(client, 30000, pipeline); 44 | 45 | // OPTION TWO: Monitor new listings using ChangeStream's hasNext() function 46 | // await monitorListingsUsingHasNext(client, 30000, pipeline); 47 | 48 | // OPTION THREE: Monitor new listings using the Stream API 49 | // await monitorListingsUsingStreamAPI(client, 30000, pipeline); 50 | 51 | } finally { 52 | // Close the connection to the MongoDB cluster 53 | await client.close(); 54 | } 55 | } 56 | 57 | main().catch(console.error); 58 | 59 | /** 60 | * Close the given change stream after the given amount of time 61 | * @param {*} timeInMs The amount of time in ms to monitor listings 62 | * @param {*} changeStream The open change stream that should be closed 63 | */ 64 | function closeChangeStream(timeInMs = 60000, changeStream) { 65 | return new Promise((resolve) => { 66 | setTimeout(() => { 67 | console.log("Closing the change stream"); 68 | changeStream.close(); 69 | resolve(); 70 | }, timeInMs) 71 | }) 72 | }; 73 | 74 | /** 75 | * Monitor listings in the listingsAndReviews collections for changes 76 | * This function uses the on() function from the EventEmitter class to monitor changes 77 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 78 | * @param {Number} timeInMs The amount of time in ms to monitor listings 79 | * @param {Object} pipeline An aggregation pipeline that determines which change events should be output to the console 80 | */ 81 | async function monitorListingsUsingEventEmitter(client, timeInMs = 60000, pipeline = []) { 82 | const collection = client.db("sample_airbnb").collection("listingsAndReviews"); 83 | 84 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#watch for the watch() docs 85 | const changeStream = collection.watch(pipeline); 86 | 87 | // ChangeStream inherits from the Node Built-in Class EventEmitter (https://nodejs.org/dist/latest-v12.x/docs/api/events.html#events_class_eventemitter). 88 | // We can use EventEmitter's on() to add a listener function that will be called whenever a change occurs in the change stream. 89 | // See https://nodejs.org/dist/latest-v12.x/docs/api/events.html#events_emitter_on_eventname_listener for the on() docs. 90 | changeStream.on('change', (next) => { 91 | console.log(next); 92 | }); 93 | 94 | // Wait the given amount of time and then close the change stream 95 | await closeChangeStream(timeInMs, changeStream); 96 | } 97 | 98 | /** 99 | * Monitor listings in the listingsAndReviews collections for changes 100 | * This function uses the hasNext() function from the MongoDB Node.js Driver's ChangeStream class to monitor changes 101 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 102 | * @param {Number} timeInMs The amount of time in ms to monitor listings 103 | * @param {Object} pipeline An aggregation pipeline that determines which change events should be output to the console 104 | */ 105 | async function monitorListingsUsingHasNext(client, timeInMs = 60000, pipeline = []) { 106 | const collection = client.db("sample_airbnb").collection("listingsAndReviews"); 107 | 108 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#watch for the watch() docs 109 | const changeStream = collection.watch(pipeline); 110 | 111 | // Set a timer that will close the change stream after the given amount of time 112 | // Function execution will continue because we are not using "await" here 113 | closeChangeStream(timeInMs, changeStream); 114 | 115 | // We can use ChangeStream's hasNext() function to wait for a new change in the change stream. 116 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/ChangeStream.html for the ChangeStream docs. 117 | try { 118 | while (await changeStream.hasNext()) { 119 | console.log(await changeStream.next()); 120 | } 121 | } catch (error) { 122 | if (changeStream.isClosed()) { 123 | console.log("The change stream is closed. Will not wait on any more changes.") 124 | } else { 125 | throw error; 126 | } 127 | } 128 | } 129 | 130 | /** 131 | * Monitor listings in the listingsAndReviews collection for changes 132 | * This function uses the Stream API (https://nodejs.org/api/stream.html) to monitor changes 133 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 134 | * @param {Number} timeInMs The amount of time in ms to monitor listings 135 | * @param {Object} pipeline An aggregation pipeline that determines which change events should be output to the console 136 | */ 137 | async function monitorListingsUsingStreamAPI(client, timeInMs = 60000, pipeline = []) { 138 | const collection = client.db('sample_airbnb').collection('listingsAndReviews'); 139 | 140 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#watch for the watch() docs 141 | const changeStream = collection.watch(pipeline); 142 | 143 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/ChangeStream.html#stream for the stream() docs 144 | changeStream.stream().pipe( 145 | new stream.Writable({ 146 | objectMode: true, 147 | write: function (doc, _, cb) { 148 | console.log(doc); 149 | cb(); 150 | } 151 | }) 152 | ); 153 | 154 | // Wait the given amount of time and then close the change stream 155 | await closeChangeStream(timeInMs, changeStream); 156 | } 157 | -------------------------------------------------------------------------------- /changeStreamsTestData.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This script can be used to create, update, and delete sample data. 3 | * This script is especially helpful when testing change streams. 4 | */ 5 | const { MongoClient } = require('mongodb'); 6 | 7 | async function main() { 8 | /** 9 | * Connection URI. Update , , and to reflect your cluster. 10 | * See https://docs.mongodb.com/drivers/node/ for more details 11 | */ 12 | const uri = "mongodb+srv://:@/sample_airbnb?retryWrites=true&w=majority"; 13 | 14 | /** 15 | * The Mongo Client you will use to interact with your database 16 | * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details 17 | * In case: '[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated...' 18 | * pass option { useUnifiedTopology: true } to the MongoClient constructor. 19 | * const client = new MongoClient(uri, {useUnifiedTopology: true}) 20 | */ 21 | const client = new MongoClient(uri); 22 | 23 | try { 24 | // Connect to the MongoDB cluster 25 | await client.connect(); 26 | 27 | // Make the appropriate DB calls 28 | const operaHouseViews = await createListing(client, { 29 | name: "Opera House Views", 30 | summary: "Beautiful apartment with views of the iconic Sydney Opera House", 31 | property_type: "Apartment", 32 | bedrooms: 1, 33 | bathrooms: 1, 34 | beds: 1, 35 | address: { 36 | market: "Sydney", 37 | country: "Australia" 38 | } 39 | }); 40 | 41 | const privateRoomInLondon = await createListing(client, { 42 | name: "Private room in London", 43 | property_type: "Apartment", 44 | bedrooms: 1, 45 | bathroom: 1 46 | }); 47 | 48 | const beautifulBeachHouse = await createListing(client, { 49 | name: "Beautiful Beach House", 50 | summary: "Enjoy relaxed beach living in this house with a private beach", 51 | bedrooms: 4, 52 | bathrooms: 2.5, 53 | beds: 7, 54 | last_review: new Date() 55 | }); 56 | 57 | await updateListing(client, operaHouseViews, { beds: 2 }); 58 | 59 | await updateListing(client, beautifulBeachHouse, { 60 | address: { 61 | market: "Sydney", 62 | country: "Australia" 63 | } 64 | }); 65 | 66 | const italianVilla = await createListing(client, { 67 | name: "Italian Villa", 68 | property_type: "Entire home/apt", 69 | bedrooms: 6, 70 | bathrooms: 4, 71 | address: { 72 | market: "Cinque Terre", 73 | country: "Italy" 74 | } 75 | }); 76 | 77 | const sydneyHarbourHome = await createListing(client, { 78 | name: "Sydney Harbour Home", 79 | bedrooms: 4, 80 | bathrooms: 2.5, 81 | address: { 82 | market: "Sydney", 83 | country: "Australia" 84 | } 85 | }); 86 | 87 | await deleteListing(client, sydneyHarbourHome); 88 | 89 | } finally { 90 | // Close the connection to the MongoDB cluster 91 | await client.close(); 92 | } 93 | } 94 | 95 | main().catch(console.error); 96 | 97 | /** 98 | * Create a new Airbnb listing 99 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 100 | * @param {Object} newListing The new listing to be added 101 | * @returns {String} The id of the new listing 102 | */ 103 | async function createListing(client, newListing) { 104 | // See http://bit.ly/Node_InsertOne for the insertOne() docs 105 | const result = await client.db("sample_airbnb").collection("listingsAndReviews").insertOne(newListing); 106 | console.log(`New listing created with the following id: ${result.insertedId}`); 107 | return result.insertedId; 108 | } 109 | 110 | /** 111 | * Update an Airbnb listing 112 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 113 | * @param {String} listingId The id of the listing you want to update 114 | * @param {object} updatedListing An object containing all of the properties to be updated for the given listing 115 | */ 116 | async function updateListing(client, listingId, updatedListing) { 117 | // See http://bit.ly/Node_updateOne for the updateOne() docs 118 | const result = await client.db("sample_airbnb").collection("listingsAndReviews").updateOne({ _id: listingId }, { $set: updatedListing }); 119 | 120 | console.log(`${result.matchedCount} document(s) matched the query criteria.`); 121 | console.log(`${result.modifiedCount} document(s) was/were updated.`); 122 | } 123 | 124 | /** 125 | * Delete an Airbnb listing 126 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 127 | * @param {String} listingId The id of the listing you want to delete 128 | */ 129 | async function deleteListing(client, listingId) { 130 | // See http://bit.ly/Node_deleteOne for the deleteOne() docs 131 | const result = await client.db("sample_airbnb").collection("listingsAndReviews").deleteOne({ _id: listingId }); 132 | 133 | console.log(`${result.deletedCount} document(s) was/were deleted.`); 134 | } 135 | -------------------------------------------------------------------------------- /connection.js: -------------------------------------------------------------------------------- 1 | const { MongoClient } = require('mongodb'); 2 | 3 | async function main() { 4 | /** 5 | * Connection URI. Update , , and to reflect your cluster. 6 | * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details 7 | */ 8 | const uri = "mongodb+srv://:@/sample_airbnb?retryWrites=true&w=majority"; 9 | 10 | /** 11 | * The Mongo Client you will use to interact with your database 12 | * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details 13 | * In case: '[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated...' 14 | * pass option { useUnifiedTopology: true } to the MongoClient constructor. 15 | * const client = new MongoClient(uri, {useUnifiedTopology: true}) 16 | */ 17 | const client = new MongoClient(uri); 18 | 19 | try { 20 | // Connect to the MongoDB cluster 21 | await client.connect(); 22 | 23 | // Make the appropriate DB calls 24 | await listDatabases(client); 25 | 26 | } catch (e) { 27 | console.error(e); 28 | } finally { 29 | // Close the connection to the MongoDB cluster 30 | await client.close(); 31 | } 32 | } 33 | 34 | main().catch(console.error); 35 | 36 | /** 37 | * Print the names of all available databases 38 | * @param {MongoClient} client A MongoClient that is connected to a cluster 39 | */ 40 | async function listDatabases(client) { 41 | databasesList = await client.db().admin().listDatabases(); 42 | 43 | console.log("Databases:"); 44 | databasesList.databases.forEach(db => console.log(` - ${db.name}`)); 45 | }; 46 | -------------------------------------------------------------------------------- /create.js: -------------------------------------------------------------------------------- 1 | const {MongoClient} = require('mongodb'); 2 | 3 | async function main(){ 4 | /** 5 | * Connection URI. Update , , and to reflect your cluster. 6 | * See https://docs.mongodb.com/drivers/node/ for more details 7 | */ 8 | const uri = "mongodb+srv://:@/sample_airbnb?retryWrites=true&w=majority"; 9 | 10 | /** 11 | * The Mongo Client you will use to interact with your database 12 | * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details 13 | * In case: '[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated...' 14 | * pass option { useUnifiedTopology: true } to the MongoClient constructor. 15 | * const client = new MongoClient(uri, {useUnifiedTopology: true}) 16 | */ 17 | const client = new MongoClient(uri); 18 | 19 | try { 20 | // Connect to the MongoDB cluster 21 | await client.connect(); 22 | 23 | // Make the appropriate DB calls 24 | 25 | // Create a single new listing 26 | await createListing(client, 27 | { 28 | name: "Lovely Loft", 29 | summary: "A charming loft in Paris", 30 | bedrooms: 1, 31 | bathrooms: 1 32 | } 33 | ); 34 | 35 | // Create 3 new listings 36 | await createMultipleListings(client, [ 37 | { 38 | name: "Infinite Views", 39 | summary: "Modern home with infinite views from the infinity pool", 40 | property_type: "House", 41 | bedrooms: 5, 42 | bathrooms: 4.5, 43 | beds: 5 44 | }, 45 | { 46 | name: "Private room in London", 47 | property_type: "Apartment", 48 | bedrooms: 1, 49 | bathroom: 1 50 | }, 51 | { 52 | name: "Beautiful Beach House", 53 | summary: "Enjoy relaxed beach living in this house with a private beach", 54 | bedrooms: 4, 55 | bathrooms: 2.5, 56 | beds: 7, 57 | last_review: new Date() 58 | } 59 | ]); 60 | } finally { 61 | // Close the connection to the MongoDB cluster 62 | await client.close(); 63 | } 64 | } 65 | 66 | main().catch(console.error); 67 | 68 | /** 69 | * Create a new Airbnb listing 70 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 71 | * @param {Object} newListing The new listing to be added 72 | */ 73 | async function createListing(client, newListing){ 74 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#insertOne for the insertOne() docs 75 | const result = await client.db("sample_airbnb").collection("listingsAndReviews").insertOne(newListing); 76 | console.log(`New listing created with the following id: ${result.insertedId}`); 77 | } 78 | 79 | /** 80 | * Create multiple Airbnb listings 81 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 82 | * @param {Object[]} newListings The new listings to be added 83 | */ 84 | async function createMultipleListings(client, newListings){ 85 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#insertMany for the insertMany() docs 86 | const result = await client.db("sample_airbnb").collection("listingsAndReviews").insertMany(newListings); 87 | 88 | console.log(`${result.insertedCount} new listing(s) created with the following id(s):`); 89 | console.log(result.insertedIds); 90 | } 91 | -------------------------------------------------------------------------------- /delete.js: -------------------------------------------------------------------------------- 1 | const { MongoClient } = require('mongodb'); 2 | 3 | async function main() { 4 | /** 5 | * Connection URI. Update , , and to reflect your cluster. 6 | * See https://docs.mongodb.com/drivers/node/ for more details 7 | */ 8 | const uri = "mongodb+srv://:@/sample_airbnb?retryWrites=true&w=majority"; 9 | 10 | /** 11 | * The Mongo Client you will use to interact with your database 12 | * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details 13 | * In case: '[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated...' 14 | * pass option { useUnifiedTopology: true } to the MongoClient constructor. 15 | * const client = new MongoClient(uri, {useUnifiedTopology: true}) 16 | */ 17 | const client = new MongoClient(uri); 18 | 19 | try { 20 | // Connect to the MongoDB cluster 21 | await client.connect(); 22 | 23 | // Make the appropriate DB calls 24 | 25 | // DELETE ONE 26 | // Check if a listing named "Cozy Cottage" exists. Run update.js if you do not have this listing. 27 | await printIfListingExists(client, "Cozy Cottage"); 28 | // Delete the "Cozy Cottage" listing 29 | await deleteListingByName(client, "Cozy Cottage"); 30 | // Check that the listing named "Cozy Cottage" no longer exists 31 | await printIfListingExists(client, "Cozy Cottage"); 32 | 33 | // DELETE MANY 34 | // Check if the listing named "Ribeira Charming Duplex" (last scraped February 16, 2019) exists 35 | await printIfListingExists(client, "Ribeira Charming Duplex"); 36 | // Check if the listing named "Horto flat with small garden" (last scraped February 11, 2019) exists 37 | await printIfListingExists(client, "Horto flat with small garden"); 38 | // Delete the listings that were scraped before February 15, 2019 39 | await deleteListingsScrapedBeforeDate(client, new Date("2019-02-15")); 40 | // Check that the listing named "Ribeira Charming Duplex" still exists 41 | await printIfListingExists(client, "Ribeira Charming Duplex"); 42 | // Check that the listing named "Horto flat with small garden" no longer exists 43 | await printIfListingExists(client, "Horto flat with small garden"); 44 | 45 | } finally { 46 | // Close the connection to the MongoDB cluster 47 | await client.close(); 48 | } 49 | } 50 | 51 | main().catch(console.error); 52 | 53 | /** 54 | * Delete an Airbnb listing with the given name. 55 | * Note: If more than one listing has the same name, only the first listing the database finds will be deleted. 56 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 57 | * @param {string} nameOfListing The name of the listing you want to delete 58 | */ 59 | async function deleteListingByName(client, nameOfListing) { 60 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#deleteOne for the deleteOne() docs 61 | const result = await client.db("sample_airbnb").collection("listingsAndReviews").deleteOne({ name: nameOfListing }); 62 | console.log(`${result.deletedCount} document(s) was/were deleted.`); 63 | } 64 | 65 | /** 66 | * Delete all listings that were last scraped prior to the given date 67 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 68 | * @param {Date} date The date to check the last_scraped property against 69 | */ 70 | async function deleteListingsScrapedBeforeDate(client, date) { 71 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#deleteMany for the deleteMany() docs 72 | const result = await client.db("sample_airbnb").collection("listingsAndReviews").deleteMany({ "last_scraped": { $lt: date } }); 73 | console.log(`${result.deletedCount} document(s) was/were deleted.`); 74 | } 75 | 76 | /** 77 | * Print information indicating if a listing with the given name exists. 78 | * If a listing has the 'last_scraped' field, print that as well. 79 | * Note: If more than one listing has the same name, only the first listing the database finds will be printed.. 80 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 81 | * @param {String} nameOfListing The name of the listing you want to find 82 | */ 83 | async function printIfListingExists(client, nameOfListing) { 84 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOne for the findOne() docs 85 | const result = await client.db("sample_airbnb").collection("listingsAndReviews").findOne({ name: nameOfListing }); 86 | 87 | if (result) { 88 | if (result.last_scraped) { 89 | console.log(`Found a listing in the collection with the name '${nameOfListing}'. Listing was last scraped ${result.last_scraped}.`); 90 | } else { 91 | console.log(`Found a listing in the collection with the name '${nameOfListing}'`); 92 | } 93 | } else { 94 | console.log(`No listings found with the name '${nameOfListing}'`); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /read.js: -------------------------------------------------------------------------------- 1 | const { MongoClient } = require('mongodb'); 2 | 3 | async function main() { 4 | /** 5 | * Connection URI. Update , , and to reflect your cluster. 6 | * See https://docs.mongodb.com/drivers/node/ for more details 7 | */ 8 | const uri = "mongodb+srv://:@/sample_airbnb?retryWrites=true&w=majority"; 9 | 10 | /** 11 | * The Mongo Client you will use to interact with your database 12 | * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details 13 | * In case: '[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated...' 14 | * pass option { useUnifiedTopology: true } to the MongoClient constructor. 15 | * const client = new MongoClient(uri, {useUnifiedTopology: true}) 16 | */ 17 | const client = new MongoClient(uri); 18 | 19 | try { 20 | // Connect to the MongoDB cluster 21 | await client.connect(); 22 | 23 | // Make the appropriate DB calls 24 | 25 | // Find the listing named "Infinite Views" that we created in create.js 26 | await findOneListingByName(client, "Infinite Views"); 27 | 28 | // Find up to 5 listings with at least 4 bedrooms and at least 2 bathrooms 29 | // If you recently ran create.js, a listing named Beautiful Beach House should be included in the results 30 | await findListingsWithMinimumBedroomsBathroomsAndMostRecentReviews(client, { 31 | minimumNumberOfBedrooms: 4, 32 | minimumNumberOfBathrooms: 2, 33 | maximumNumberOfResults: 5 34 | }); 35 | 36 | } finally { 37 | // Close the connection to the MongoDB cluster 38 | await client.close(); 39 | } 40 | } 41 | 42 | main().catch(console.error); 43 | 44 | /** 45 | * Print an Airbnb listing with the given name 46 | * Note: If more than one listing has the same name, only the first listing the database finds will be printed. 47 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 48 | * @param {String} nameOfListing The name of the listing you want to find 49 | */ 50 | async function findOneListingByName(client, nameOfListing) { 51 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOne for the findOne() docs 52 | const result = await client.db("sample_airbnb").collection("listingsAndReviews").findOne({ name: nameOfListing }); 53 | 54 | if (result) { 55 | console.log(`Found a listing in the collection with the name '${nameOfListing}':`); 56 | console.log(result); 57 | } else { 58 | console.log(`No listings found with the name '${nameOfListing}'`); 59 | } 60 | } 61 | 62 | /** 63 | * Print Airbnb listings with a minimum number of bedrooms and bathrooms. 64 | * Results will be limited to the designated maximum number of results. 65 | * Results will be sorted by the date of the last review in descending order. 66 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 67 | * @param {object} queryParams The query params object 68 | * @param {number} queryParams.minimumNumberOfBedrooms The minimum number of bedrooms 69 | * @param {number} queryParams.minimumNumberOfBathrooms The minimum number of bathrooms 70 | * @param {number} queryParams.maximumNumberOfResults The maximum number of Airbnb listings to be printed 71 | */ 72 | async function findListingsWithMinimumBedroomsBathroomsAndMostRecentReviews(client, { 73 | minimumNumberOfBedrooms = 0, 74 | minimumNumberOfBathrooms = 0, 75 | maximumNumberOfResults = Number.MAX_SAFE_INTEGER 76 | } = {}) { 77 | 78 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#find for the find() docs 79 | const cursor = client.db("sample_airbnb").collection("listingsAndReviews") 80 | .find({ 81 | bedrooms: { $gte: minimumNumberOfBedrooms }, 82 | bathrooms: { $gte: minimumNumberOfBathrooms } 83 | } 84 | ) 85 | .sort({ last_review: -1 }) 86 | .limit(maximumNumberOfResults); 87 | 88 | // Store the results in an array 89 | const results = await cursor.toArray(); 90 | 91 | // Print the results 92 | if (results.length > 0) { 93 | console.log(`Found listing(s) with at least ${minimumNumberOfBedrooms} bedrooms and ${minimumNumberOfBathrooms} bathrooms:`); 94 | results.forEach((result, i) => { 95 | const date = new Date(result.last_review).toDateString(); 96 | 97 | console.log(); 98 | console.log(`${i + 1}. name: ${result.name}`); 99 | console.log(` _id: ${result._id}`); 100 | console.log(` bedrooms: ${result.bedrooms}`); 101 | console.log(` bathrooms: ${result.bathrooms}`); 102 | console.log(` most recent review date: ${date}`); 103 | }); 104 | } else { 105 | console.log(`No listings found with at least ${minimumNumberOfBedrooms} bedrooms and ${minimumNumberOfBathrooms} bathrooms`); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /template.js: -------------------------------------------------------------------------------- 1 | const { MongoClient } = require('mongodb'); 2 | 3 | async function main() { 4 | /** 5 | * Connection URI. Update , , and to reflect your cluster. 6 | * See https://docs.mongodb.com/drivers/node/ for more details 7 | */ 8 | const uri = "mongodb+srv://:@/sample_airbnb?retryWrites=true&w=majority"; 9 | 10 | /** 11 | * The Mongo Client you will use to interact with your database 12 | * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details 13 | * In case: '[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated...' 14 | * pass option { useUnifiedTopology: true } to the MongoClient constructor. 15 | * const client = new MongoClient(uri, {useUnifiedTopology: true}) 16 | */ 17 | const client = new MongoClient(uri); 18 | 19 | try { 20 | // Connect to the MongoDB cluster 21 | await client.connect(); 22 | 23 | // Make the appropriate DB calls 24 | 25 | } finally { 26 | // Close the connection to the MongoDB cluster 27 | await client.close(); 28 | } 29 | } 30 | 31 | main().catch(console.error); 32 | 33 | // Add functions that make DB calls here 34 | -------------------------------------------------------------------------------- /transaction-bankingexample.js: -------------------------------------------------------------------------------- 1 | const { MongoClient } = require('mongodb'); 2 | 3 | // In MongoDB 4.2 and earlier, CRUD operations in transactions must be on existing collections 4 | // See https://docs.mongodb.com/manual/core/transactions/#transactions-api for more information 5 | 6 | // Before running this script... 7 | // 1. Create a database named 'banking' 8 | // 2. Create a collection named 'accounts' in the database 9 | // 3. Create two documents in the 'accounts' collection: 10 | // {"_id":"account1", "balance":500} 11 | // {"_id":"account2", "balance":0} 12 | // 4: Optional: add schema validation to ensure an account balance cannot drop below 0. 13 | // See https://docs.mongodb.com/manual/core/schema-validation/ for details on how to 14 | // enable schema validation. Configuring schema validation in MongoDB Compass is an 15 | // easy way to add schema validation to an existing database: https://docs.mongodb.com/compass/current/validation/ 16 | // 17 | // { 18 | // $jsonSchema: { 19 | // properties: { 20 | // balance: { 21 | // minimum: 0, 22 | // description: 'account balance cannot be negative' 23 | // } 24 | // } 25 | // } 26 | // } 27 | 28 | async function main() { 29 | /** 30 | * Connection URI. Update , , and to reflect your cluster. 31 | * See https://docs.mongodb.com/drivers/node/ for more details 32 | */ 33 | const uri = "mongodb+srv://:@/banking?retryWrites=true&w=majority"; 34 | 35 | /** 36 | * The Mongo Client you will use to interact with your database 37 | * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details 38 | */ 39 | const client = new MongoClient(uri); 40 | 41 | try { 42 | // Connect to the MongoDB cluster 43 | await client.connect(); 44 | 45 | // Transfer $100 from "account1" to "account2" 46 | await transferMoney(client, "account1", "account2", 100); 47 | 48 | } finally { 49 | // Close the connection to the MongoDB cluster 50 | await client.close(); 51 | } 52 | } 53 | 54 | main().catch(console.error); 55 | 56 | /** 57 | * Transfer money from one bank account to another using 58 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the banking database 59 | * @param {String} account1 The _id of the account where money should be subtracted 60 | * @param {String} account2 The _id of the account where money should be added 61 | * @param {Number} amount The amount of money to be transferred 62 | */ 63 | async function transferMoney(client, account1, account2, amount) { 64 | 65 | /** 66 | * The accounts collection in the banking database 67 | */ 68 | const accountsCollection = client.db("banking").collection("accounts"); 69 | 70 | // Step 1: Start a Client Session 71 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html#startSession for the startSession() docs 72 | const session = client.startSession(); 73 | 74 | // Step 2: Optional. Define options for the transaction 75 | const transactionOptions = { 76 | readPreference: 'primary', 77 | readConcern: { level: 'local' }, 78 | writeConcern: { w: 'majority' } 79 | }; 80 | 81 | try { 82 | // Step 3: Use withTransaction to start a transaction, execute the callback, and commit (or abort on error) 83 | // Note: The callback for withTransaction MUST be async and/or return a Promise. 84 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/ClientSession.html#withTransaction for the withTransaction() docs 85 | const transactionResults = await session.withTransaction(async () => { 86 | 87 | // Important:: You must pass the session to each of the operations 88 | 89 | // Remove the money from the first account 90 | const subtractMoneyResults = await accountsCollection.updateOne( 91 | { _id: account1 }, 92 | { $inc: { balance: amount * -1 } }, 93 | { session }); 94 | console.log(`${subtractMoneyResults.matchedCount} document(s) found in the accounts collection with _id ${account1}.`); 95 | console.log(`${subtractMoneyResults.modifiedCount} document(s) was/were updated to remove the money.`); 96 | if (subtractMoneyResults.modifiedCount !== 1) { 97 | await session.abortTransaction(); 98 | return; 99 | } 100 | 101 | // Add the money to the second account 102 | const addMoneyResults = await accountsCollection.updateOne( 103 | { _id: account2 }, 104 | { $inc: { balance: amount } }, 105 | { session }); 106 | console.log(`${addMoneyResults.matchedCount} document(s) found in the accounts collection with _id ${account2}.`); 107 | console.log(`${addMoneyResults.modifiedCount} document(s) was/were updated to add the money.`); 108 | if (addMoneyResults.modifiedCount !== 1) { 109 | await session.abortTransaction(); 110 | return; 111 | } 112 | 113 | }, transactionOptions); 114 | 115 | if (transactionResults) { 116 | console.log("The money was successfully transferred. Database operations from the transaction are now visible outside the transaction."); 117 | } else { 118 | console.log("The money was not transferred. The transaction was intentionally aborted."); 119 | } 120 | } catch (e) { 121 | console.log("The money was not transferred. The transaction was aborted due to an unexpected error: " + e); 122 | } finally { 123 | // Step 4: End the session 124 | await session.endSession(); 125 | } 126 | 127 | } 128 | 129 | -------------------------------------------------------------------------------- /transaction-inventoryexample.js: -------------------------------------------------------------------------------- 1 | const { MongoClient } = require('mongodb'); 2 | 3 | // In MongoDB 4.2 and earlier, CRUD operations in transactions must be on existing collections 4 | // See https://docs.mongodb.com/manual/core/transactions/#transactions-api for more information 5 | 6 | // Before running this script... 7 | // 1. Create a database named 'book-store' 8 | // 2. Create a collection named 'orders' in the database 9 | // 3. Create a collection named 'inventory' in the database 10 | // 3. Create a document in the 'inventory' collection: 11 | // { "_id": "parks-rec-book", "name": "The Ultimate Parks and Rec Book for the Ultimate Fans", "numberInStock": 5 } 12 | // 4: Optional: Add schema validation to the 'inventory' collection to ensure the number of items in stock cannot drop below 0. 13 | // See https://docs.mongodb.com/manual/core/schema-validation/ for details on how to 14 | // enable schema validation. Configuring schema validation in MongoDB Compass is an 15 | // easy way to add schema validation to an existing database: https://docs.mongodb.com/compass/current/validation/ 16 | // 17 | // { 18 | // $jsonSchema: { 19 | // properties: { 20 | // numberInStock: { 21 | // minimum: 0, 22 | // description: 'numberInStock cannot be negative' 23 | // } 24 | // } 25 | // } 26 | // } 27 | 28 | async function main() { 29 | /** 30 | * Connection URI. Update , , and to reflect your cluster. 31 | * See https://docs.mongodb.com/drivers/node/ for more details 32 | */ 33 | const uri = "mongodb+srv://:@/book-store?retryWrites=true&w=majority"; 34 | 35 | /** 36 | * The Mongo Client you will use to interact with your database 37 | * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details 38 | */ 39 | const client = new MongoClient(uri); 40 | 41 | try { 42 | // Connect to the MongoDB cluster 43 | await client.connect(); 44 | 45 | // User1 purchases 1 copy of parks-rec-book 46 | await purchaseBook(client, "User1", "parks-rec-book", 1, "paid"); 47 | 48 | } finally { 49 | // Close the connection to the MongoDB cluster 50 | await client.close(); 51 | } 52 | } 53 | 54 | main().catch(console.error); 55 | 56 | /** 57 | * Purchase a book 58 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the book-store database 59 | * @param {String} userId The _id of the user who is purchasing the book 60 | * @param {String} bookId The _id of the book being purchased 61 | * @param {Number} quantity The number of copies being purchased 62 | * @param {String} status The order status 63 | */ 64 | async function purchaseBook(client, userId, bookId, quantity, status) { 65 | 66 | /** 67 | * The orders collection in the book-store database 68 | */ 69 | const ordersCollection = client.db("book-store").collection("orders"); 70 | 71 | /** 72 | * The inventory collection in the book-store database 73 | */ 74 | const inventoryCollection = client.db("book-store").collection("inventory"); 75 | 76 | // Step 1: Start a Client Session 77 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html#startSession for the startSession() docs 78 | const session = client.startSession(); 79 | 80 | // Step 2: Optional. Define options for the transaction 81 | const transactionOptions = { 82 | readPreference: 'primary', 83 | readConcern: { level: 'local' }, 84 | writeConcern: { w: 'majority' } 85 | }; 86 | 87 | try { 88 | // Step 3: Use withTransaction to start a transaction, execute the callback, and commit (or abort on error) 89 | // Note: The callback for withTransaction MUST be async and/or return a Promise. 90 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/ClientSession.html#withTransaction for the withTransaction() docs 91 | const transactionResults = await session.withTransaction(async () => { 92 | 93 | // Important:: You must pass the session to each of the operations 94 | 95 | // Update the inventory to reflect the book has been sold 96 | const updateInventoryResults = await inventoryCollection.updateOne( 97 | { _id: bookId }, 98 | { $inc: { numberInStock: quantity * -1 } }, 99 | { session }); 100 | console.log(`${updateInventoryResults.matchedCount} document(s) found in the inventory collection with _id ${bookId}.`); 101 | console.log(`${updateInventoryResults.modifiedCount} document(s) was/were updated.`); 102 | if (updateInventoryResults.modifiedCount !== 1) { 103 | await session.abortTransaction(); 104 | return; 105 | } 106 | 107 | // Record the order in the orders collection 108 | const insertOrderResults = await ordersCollection.insertOne( 109 | { "userId": userId , bookId: bookId, quantity: quantity, status: status }, 110 | { session }); 111 | console.log(`New order recorded with the following id: ${insertOrderResults.insertedId}`); 112 | 113 | }, transactionOptions); 114 | 115 | if (transactionResults) { 116 | console.log("The order was successfully processed. Database operations from the transaction are now visible outside the transaction."); 117 | } else { 118 | console.log("The order was not successful. The transaction was intentionally aborted."); 119 | } 120 | } catch (e) { 121 | console.log("The order was not successful. The transaction was aborted due to an unexpected error: " + e); 122 | } finally { 123 | // Step 4: End the session 124 | await session.endSession(); 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /transaction.js: -------------------------------------------------------------------------------- 1 | const { MongoClient } = require('mongodb'); 2 | 3 | // In MongoDB 4.2 and earlier, CRUD operations in transactions must be on existing collections 4 | // See https://docs.mongodb.com/manual/core/transactions/#transactions-api for more information 5 | // Be sure you have run usersCollection.js prior to running this script 6 | 7 | async function main() { 8 | /** 9 | * Connection URI. Update , , and to reflect your cluster. 10 | * See https://docs.mongodb.com/drivers/node/ for more details 11 | */ 12 | const uri = "mongodb+srv://:@/sample_airbnb?retryWrites=true&w=majority"; 13 | 14 | /** 15 | * The Mongo Client you will use to interact with your database 16 | * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details 17 | * In case: '[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated...' 18 | * pass option { useUnifiedTopology: true } to the MongoClient constructor. 19 | * const client = new MongoClient(uri, {useUnifiedTopology: true}) 20 | */ 21 | const client = new MongoClient(uri); 22 | 23 | try { 24 | // Connect to the MongoDB cluster 25 | await client.connect(); 26 | 27 | // Make the appropriate DB calls 28 | 29 | await createReservation(client, 30 | "leslie@example.com", 31 | "Infinite Views", 32 | [new Date("2019-12-31"), new Date("2020-01-01")], 33 | { pricePerNight: 180, specialRequests: "Late checkout", breakfastIncluded: true }); 34 | 35 | } finally { 36 | // Close the connection to the MongoDB cluster 37 | await client.close(); 38 | } 39 | } 40 | 41 | main().catch(console.error); 42 | 43 | /** 44 | * Create a reservation by storing information in both the users collection and the listingsAndReviews collection 45 | * Note: this function assumes there is only one Airbnb listing in the collection with the given name. If more than 46 | * listing exists with the given name, a reservation will be created for the first listing the database finds. 47 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 48 | * @param {String} userEmail The email address of the user who is creating the reservation 49 | * @param {String} nameOfListing The name of the Airbnb listing to be reserved 50 | * @param {Array.Date} reservationDates An array of the date(s) for the reservation 51 | * @param {Object} reservationDetails An object containing additional reservation details that need to be stored with the reservation 52 | */ 53 | async function createReservation(client, userEmail, nameOfListing, reservationDates, reservationDetails) { 54 | 55 | /** 56 | * The users collection in the sample_airbnb database 57 | */ 58 | const usersCollection = client.db("sample_airbnb").collection("users"); 59 | 60 | /** 61 | * The listingsAndReviews collection in the sample_airbnb database 62 | */ 63 | const listingsAndReviewsCollection = client.db("sample_airbnb").collection("listingsAndReviews"); 64 | 65 | /** 66 | * The reservation document that will be added to the users collection document for this user 67 | */ 68 | const reservation = createReservationDocument(nameOfListing, reservationDates, reservationDetails); 69 | 70 | // Step 1: Start a Client Session 71 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html#startSession for the startSession() docs 72 | const session = client.startSession(); 73 | 74 | // Step 2: Optional. Define options for the transaction 75 | const transactionOptions = { 76 | readPreference: 'primary', 77 | readConcern: { level: 'local' }, 78 | writeConcern: { w: 'majority' } 79 | }; 80 | 81 | try { 82 | // Step 3: Use withTransaction to start a transaction, execute the callback, and commit (or abort on error) 83 | // Note: The callback for withTransaction MUST be async and/or return a Promise. 84 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/ClientSession.html#withTransaction for the withTransaction() docs 85 | const transactionResults = await session.withTransaction(async () => { 86 | 87 | // Important:: You must pass the session to each of the operations 88 | 89 | // Add a reservation to the reservations array for the appropriate document in the users collection 90 | const usersUpdateResults = await usersCollection.updateOne( 91 | { email: userEmail }, 92 | { $addToSet: { reservations: reservation } }, 93 | { session }); 94 | console.log(`${usersUpdateResults.matchedCount} document(s) found in the users collection with the email address ${userEmail}.`); 95 | console.log(`${usersUpdateResults.modifiedCount} document(s) was/were updated to include the reservation.`); 96 | 97 | // Check if the Airbnb listing is already reserved for those dates. If so, abort the transaction. 98 | const isListingReservedResults = await listingsAndReviewsCollection.findOne( 99 | { name: nameOfListing, datesReserved: { $in: reservationDates } }, 100 | { session }); 101 | if (isListingReservedResults) { 102 | await session.abortTransaction(); 103 | console.error("This listing is already reserved for at least one of the given dates. The reservation could not be created."); 104 | console.error("Any operations that already occurred as part of this transaction will be rolled back.") 105 | return; 106 | } 107 | 108 | // Add the reservation dates to the datesReserved array for the appropriate document in the listingsAndRewiews collection 109 | const listingsAndReviewsUpdateResults = await listingsAndReviewsCollection.updateOne( 110 | { name: nameOfListing }, 111 | { $addToSet: { datesReserved: { $each: reservationDates } } }, 112 | { session }); 113 | console.log(`${listingsAndReviewsUpdateResults.matchedCount} document(s) found in the listingsAndReviews collection with the name ${nameOfListing}.`); 114 | console.log(`${listingsAndReviewsUpdateResults.modifiedCount} document(s) was/were updated to include the reservation dates.`); 115 | 116 | }, transactionOptions); 117 | 118 | if (transactionResults) { 119 | console.log("The reservation was successfully created."); 120 | } else { 121 | console.log("The transaction was intentionally aborted."); 122 | } 123 | } catch (e) { 124 | console.log("The transaction was aborted due to an unexpected error: " + e); 125 | } finally { 126 | // Step 4: End the session 127 | await session.endSession(); 128 | } 129 | 130 | } 131 | 132 | /** 133 | * A helper function that generates a reservation document 134 | * @param {String} nameOfListing The name of the Airbnb listing to be reserved 135 | * @param {Array.Date} reservationDates An array of the date(s) for the reservation 136 | * @param {Object} reservationDetails An object containing additional reservation details that need to be stored with the reservation 137 | * @returns {Object} The reservation document 138 | */ 139 | function createReservationDocument(nameOfListing, reservationDates, reservationDetails) { 140 | // Create the reservation 141 | let reservation = { 142 | name: nameOfListing, 143 | dates: reservationDates, 144 | } 145 | 146 | // Add additional properties from reservationDetails to the reservation 147 | for (let detail in reservationDetails) { 148 | reservation[detail] = reservationDetails[detail]; 149 | } 150 | 151 | return reservation; 152 | } 153 | -------------------------------------------------------------------------------- /update.js: -------------------------------------------------------------------------------- 1 | const { MongoClient } = require('mongodb'); 2 | 3 | async function main() { 4 | /** 5 | * Connection URI. Update , , and to reflect your cluster. 6 | * See https://docs.mongodb.com/drivers/node/ for more details 7 | */ 8 | const uri = "mongodb+srv://:@/sample_airbnb?retryWrites=true&w=majority"; 9 | 10 | /** 11 | * The Mongo Client you will use to interact with your database 12 | * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details 13 | * In case: '[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated...' 14 | * pass option { useUnifiedTopology: true } to the MongoClient constructor. 15 | * const client = new MongoClient(uri, {useUnifiedTopology: true}) 16 | */ 17 | const client = new MongoClient(uri); 18 | 19 | try { 20 | // Connect to the MongoDB cluster 21 | await client.connect(); 22 | 23 | // Make the appropriate DB calls 24 | 25 | // UPDATE 26 | // Print the Infinite Views listing 27 | await findListingByName(client, "Infinite Views"); 28 | // Update the Infinite Views listing to have 6 bedrooms and 8 beds 29 | await updateListingByName(client, "Infinite Views", { bedrooms: 6, beds: 8 }); 30 | // Print the updated Infinite Views listing 31 | await findListingByName(client, "Infinite Views"); 32 | 33 | // UPSERT 34 | // Check if a listing named Cozy Cottage is in the db 35 | await findListingByName(client, "Cozy Cottage"); 36 | // Upsert the Cozy Cottage listing 37 | await upsertListingByName(client, "Cozy Cottage", { name: "Cozy Cottage", bedrooms: 2, bathrooms: 1 }); 38 | // Print the details of the Cozy Cottage listing 39 | await findListingByName(client, "Cozy Cottage"); 40 | // Upsert the Cozy Cottage listing 41 | await upsertListingByName(client, "Cozy Cottage", { beds: 2 }); 42 | // Print the details of the Cozy Cottage listing 43 | await findListingByName(client, "Cozy Cottage"); 44 | 45 | // UPDATE MANY 46 | // Update all listings so they have a property type 47 | await updateAllListingsToHavePropertyType(client); 48 | // Print the details of the Cozy Cottage listing that should now have a property type 49 | await findListingByName(client, "Cozy Cottage"); 50 | 51 | } finally { 52 | // Close the connection to the MongoDB cluster 53 | await client.close(); 54 | } 55 | } 56 | 57 | main().catch(console.error); 58 | 59 | /** 60 | * Update an Airbnb listing with the given name 61 | * Note: If more than one listing has the same name, only the first listing the database finds will be updated. 62 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 63 | * @param {string} nameOfListing The name of the listing you want to update 64 | * @param {object} updatedListing An object containing all of the properties to be updated for the given listing 65 | */ 66 | async function updateListingByName(client, nameOfListing, updatedListing) { 67 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#updateOne for the updateOne() docs 68 | const result = await client.db("sample_airbnb").collection("listingsAndReviews").updateOne({ name: nameOfListing }, { $set: updatedListing }); 69 | 70 | console.log(`${result.matchedCount} document(s) matched the query criteria.`); 71 | console.log(`${result.modifiedCount} document(s) was/were updated.`); 72 | } 73 | 74 | /** 75 | * Upsert an Airbnb listing with the given name. 76 | * If a listing with the given name exists, it will be updated. 77 | * If a listing with the given name does not exist, it will be inserted. 78 | * Note: If more than one listing has the same name, only the first listing the database finds will be updated. 79 | * Note: For educational purposes, we have split the update and upsert functionality into separate functions. 80 | * Another option is to have a single function where a boolean param indicates if the update should be an upsert. 81 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 82 | * @param {string} nameOfListing The name of the listing you want to upsert 83 | * @param {object} updatedListing An object containing all of the properties to be upserted for the given listing 84 | */ 85 | async function upsertListingByName(client, nameOfListing, updatedListing) { 86 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#updateOne for the updateOne() docs 87 | const result = await client.db("sample_airbnb").collection("listingsAndReviews").updateOne({ name: nameOfListing }, { $set: updatedListing }, { upsert: true }); 88 | console.log(`${result.matchedCount} document(s) matched the query criteria.`); 89 | 90 | if (result.upsertedCount > 0) { 91 | console.log(`One document was inserted with the id ${result.upsertedId._id}`); 92 | } else { 93 | console.log(`${result.modifiedCount} document(s) was/were updated.`); 94 | } 95 | } 96 | 97 | /** 98 | * Update all Airbnb listings that do not have a property type so they have property_type 'Unknown' 99 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 100 | */ 101 | async function updateAllListingsToHavePropertyType(client) { 102 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#updateMany for the updateMany() docs 103 | const result = await client.db("sample_airbnb").collection("listingsAndReviews").updateMany({ property_type: { $exists: false } }, { $set: { property_type: "Unknown" } }); 104 | console.log(`${result.matchedCount} document(s) matched the query criteria.`); 105 | console.log(`${result.modifiedCount} document(s) was/were updated.`); 106 | } 107 | 108 | /** 109 | * Print an Airbnb listing with the given name 110 | * Note: If more than one listing has the same name, only the first listing the database finds will be printed. 111 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 112 | * @param {String} nameOfListing The name of the listing you want to find 113 | */ 114 | async function findListingByName(client, nameOfListing) { 115 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOne for the findOne() docs 116 | const result = await client.db("sample_airbnb").collection("listingsAndReviews").findOne({ name: nameOfListing }); 117 | 118 | if (result) { 119 | console.log(`Found a listing in the db with the name '${nameOfListing}':`); 120 | console.log(result); 121 | } else { 122 | console.log(`No listings found with the name '${nameOfListing}'`); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /usersCollection.js: -------------------------------------------------------------------------------- 1 | const { MongoClient } = require('mongodb'); 2 | 3 | /** 4 | * This script creates 3 new users in the users collection in the sample_airbnb database. 5 | * The users collection does not need to exist before running this script. 6 | * This script also creates a unique index on the email field in the users collection. 7 | * 8 | * You will see "duplicate key" errors if you attempt to run this script more than once 9 | * without dropping the documents in the users collection, because the unique index will 10 | * not allow you to insert more than one document into the collection with the same email address. 11 | */ 12 | 13 | async function main() { 14 | /** 15 | * Connection URI. Update , , and to reflect your cluster. 16 | * See https://docs.mongodb.com/drivers/node/ for more details 17 | */ 18 | const uri = "mongodb+srv://:@/sample_airbnb?retryWrites=true&w=majority"; 19 | 20 | /** 21 | * The Mongo Client you will use to interact with your database 22 | * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details 23 | * In case: '[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated...' 24 | * pass option { useUnifiedTopology: true } to the MongoClient constructor. 25 | * const client = new MongoClient(uri, {useUnifiedTopology: true}) 26 | */ 27 | const client = new MongoClient(uri); 28 | 29 | try { 30 | // Connect to the MongoDB cluster 31 | await client.connect(); 32 | 33 | // Make the appropriate DB calls 34 | 35 | // Create 3 new users in the users collection 36 | await createMultipleUsers(client, [ 37 | { 38 | email: "leslie@example.com", 39 | name: "Leslie Yepp" 40 | }, 41 | { 42 | email: "april@example.com", 43 | name: "April Ludfence" 44 | }, 45 | { 46 | email: "tom@example.com", 47 | name: "Tom Haverdodge" 48 | } 49 | ]); 50 | 51 | // Create a unique index on the email field in the users collection. 52 | // Note that if you run this script when you already have duplicate emails in the user collection, 53 | // MongoDB will be unable to create the unique index. 54 | const createIndexResults = await client.db("sample_airbnb").collection("users").createIndex({ "email": 1 }, { unique: true }); 55 | console.log(`Index successfully created: ${createIndexResults}`); 56 | 57 | } finally { 58 | // Close the connection to the MongoDB cluster 59 | await client.close(); 60 | } 61 | } 62 | 63 | main().catch(console.error); 64 | 65 | /** 66 | * Create multiple users 67 | * @param {MongoClient} client A MongoClient that is connected to a cluster with the sample_airbnb database 68 | * @param {Object[]} newUsers The new users to be added 69 | */ 70 | async function createMultipleUsers(client, newUsers) { 71 | // See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#insertMany for the insertMany() docs 72 | const result = await client.db("sample_airbnb").collection("users").insertMany(newUsers); 73 | 74 | console.log(`${result.insertedCount} new user(s) created with the following id(s):`); 75 | console.log(result.insertedIds); 76 | } 77 | --------------------------------------------------------------------------------