What is Mongoose
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.
ODM's like Mongoose "map documents coming from a MongoDB into useable JavaScript objects". Mongoose provides ways for us to model out our applications data and define a schema.
What is a schema?
- A schema defines the structure of your "Collection's, Documents". A Mongoose schema maps directly to a MongoDB collection.
Mongoose offers easy ways to validate data and build complex queries from JavaScript. Mongoose claims it is "elegant MongoDB object modeling for node.Js."
Installing Mongoose
To get Mongoose installed, we need to get our working environment set up with express and node.js. A quick refresher can be found here.
Here are the basic steps:
- set up our "Parent Directory" which we're calling express
- run npm init to set up our package.json file
- run npm i express to install express
- run npm i nodemon to install nodemon
- create our index.js file in our express directory
And now with our working environment set up, we can writ the code in index.js to connect mongoose to our dataBase. We're going to create a Movies App for learning purposes, so our Js code will look like this:
- JavaScript
- const mongoose = require('mongoose');
- mongoose.connect( 'mongodb://127.0.0.1:27017/movieApp' )
-
- .then( () => {
- console.log('Mongoose connected on port mongodb://127.0.0.1:27017/');
- console.log('Connected to movieApp DB');
- })
- .catch(err => {
- console.log('Connection Error!');
- console.log(err);
- })
And now we can run nodemon index.js.
If mongoose successfully connects to our movieApp DB, we'll get the "Connected" message, if not, we'll get the error.
So we've learned how to set up our working environment, install mongoose and connect it to our dataBase. With all the setup done, we can now actually start using mongoose.
Back to Top