https://youtu.be/nBZYUjyO9hY

Before we can start accessing our database, we have to install MongoDB and Mongoose on our project. We can do this through NPM, and we can require Mongoose to use the connect() method to make a connection to our database.

  1. In Glitch, open the terminal from Tools → Terminal, and run this command to install MongoDB:

    npm install mongodb
    
  2. Require Mongoose in myApp.js and assign it to the variable mongoose:

    let mongoose = require('mongoose')
    
  3. Call the connect() method on mongoose, with the full URI and the options specified:

    let uri = 'mongodb+srv://<USERNAME>:' + process.env.PW + '@xxxxxx.xxxxx.mongodb.net/<DATABASE>?retryWrites=true&w=majority'
    mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
    

Here, I've set the password to an Environment Variable called PW

Use the .env File

Concepts

mongoose.connect()

Opens the default mongoose connection.

Mongoose

require()

Used to import modules, JSON, and local files. Modules can be imported from node_modules. Local modules and JSON files can be imported using a relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be resolved against the directory named by __dirname (if defined) or the current working directory. The relative paths of POSIX style are resolved in an OS independent fashion, meaning that the examples above will work on Windows in the same way they would on Unix systems.

Node.js v14.5.0 Documentation

dependencies

Dependencies are specified in a simple object that maps a package name to a version range. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL.

package.json

All npm packages contain a file, usually in the project root, called package.json - this file holds various metadata relevant to the project. This file is used to give information to npm that allows it to identify the project as well as handle the project's dependencies. It can also contain other metadata such as a project description, the version of the project in a particular distribution, license information, even configuration data - all of which can be vital to both npm and to the end users of the package. The package.json file is normally located at the root directory of a Node.js project.

What is the file package.json? | Node.js