Connecting with Mongoose
Mongoose is a library that connects Node.js code to MongoDB. It turns plain JavaScript objects into database documents.
Import Mongoose
This line loads the Mongoose library.
import mongoose from 'mongoose';Connect
This line opens the link to the notes database.
await mongoose.connect('mongodb://localhost:27017/notes');Check the link
This line prints 1 when the link is open.
console.log(mongoose.connection.readyState);Example
import mongoose from 'mongoose';
await mongoose.connect('mongodb://localhost:27017/notes');
console.log(mongoose.connection.readyState);
console.log('Connected.');
await mongoose.disconnect();Key points
- Mongoose is an npm package, so it installs with npm.
- The connect method opens a link to a MongoDB database.
- The connection string names the server and the database.
- The database in this course is named notes.
- The readyState value is 1 when the link is open.
In this example, the import line loads Mongoose. The connect line opens the link to the notes database. The first print shows the ready state, and 1 means open. The second print shows a short message. The disconnect line closes the link.
Note
The course uses a local MongoDB at mongodb://localhost:27017/notes.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does mongoose.connect do?