|
| 1 | +const {MongoClient} = require('mongodb'); |
| 2 | + |
| 3 | +async function main(){ |
| 4 | + /** |
| 5 | + * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster. |
| 6 | + * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details |
| 7 | + */ |
| 8 | + const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?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.3/api/MongoClient.html for more details |
| 13 | + */ |
| 14 | + const client = new MongoClient(uri); |
| 15 | + |
| 16 | + try { |
| 17 | + // Connect to the MongoDB cluster |
| 18 | + await client.connect(); |
| 19 | + |
| 20 | + // Access the listingsAndReviews collection that is stored in the sample_airbnb DB |
| 21 | + let collection = client.db("sample_airbnb").collection("listingsAndReviews"); |
| 22 | + |
| 23 | + // Make the appropriate DB calls |
| 24 | + await printFiveListings(collection); |
| 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.err); |
| 35 | + |
| 36 | +/** |
| 37 | + * Print the names of five Airbnb listings |
| 38 | + * @param {Collection} collection The collection to search |
| 39 | + */ |
| 40 | +async function printFiveListings(collection){ |
| 41 | + let cursor = await collection.find({}).limit(5); |
| 42 | + let docs = await cursor.toArray(); |
| 43 | + |
| 44 | + console.log("Found Airbnb listings in the database:"); |
| 45 | + docs.forEach(doc => console.log(` - ${doc.name}`)); |
| 46 | +}; |
0 commit comments