Step 7

Open the QuickNote-API in VSCode. Then, install mongoose:

npm install mongoose

Create a new folder at the root of this project and call it scripts. Add a file sampleNotes.js to this folder with the following content.

const mongoose = require("mongoose");

console.log(mongoose);

Run this script using the following command in the terminal.

node scripts/sampleNotes.js 

Mongoose is an object document mapping (ODM) that sits on top of Node's MongoDB driver.

Update the sampleNotes.js as follows:

const mongoose = require("mongoose");

// TODO replace <password> with the password for quicknote-admin
const URI = `mongodb+srv://quicknote-admin:<password>@quicknote.ydsfc.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;

mongoose
  .connect(URI)
  .then(() => {
    console.log("Connected to MongoDB!");
  })
  .catch((err) => {
    console.log(err);
  });

Save the file and rerun it! If all goes well, you will see the following message in the terminal.

Connected to MongoDB!

Stop the script by pressing the Ctrl + C keys.

In the above snippet, we are using the connect method on mongoose object to establish a connection to our MongoDB cluster in the cloud. The connect method takes the MongoDB URI and returns a Promise.

Resources

It is not required to use Mongoose with MongoDB, but there are advantages in doing so! For example, read Top 4 Reasons to Use Mongoose with MongoDB.