DEV Community

vblaha
vblaha

Posted on

Mongoose

Introducing Mongoose ODM: Sturdy Framework and Tight Pivots!

bmx
If you found this page by searching for BMX images, here's a fun history of Mongoose bikes. If not and you still read it, then that was another time-sucking distraction, compliments of the internet. Focus! Here we'll be talking about Mongoose the JS framework, which has made its own name to JS developers as a sturdy workhorse that traverses well within a full JS stack. The following diagram helps visualize how Mongoose works to deliver database information cyclically(pun intended) with our Mongo client and Node.

model

To use Mongoose, we have to install most of the items seen above in the diagram. Mongoose is designed to work in tandem with MongoDB running in the background, so establishing a connection is what we'll focus on first.
You can download MongoDB here.
Start mongoDB in the terminal using the command: mongod
Then open a second terminal window and run the command: mongo

You'll also need to download Node.JS here. After you've successfully installed Node, install your mongoose package with the following commmand: npm install mongoose --save

We have to create an initial connection with MongoDB through mongoose, and the best way to do that varies by OS, so here is the to the Mongoose documentation.

Mongoose writes database collections in the form of schemas. Schemas function as templates or parameters for data sets, giving a collection more structure, organization and readability before moving the information between the frontend and backend.
Here's an example of what a schema looks like:

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
username: String,
email: String,
unique:true,
}, {timestamps: true});

module.exports = mongoose.model('User', UserSchema);

There are a few different Schema types:

String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array
Decimal128
Map

Alternately, you can use the type:property way of declaring a Schema type.Using the word 'require' acts as a validator to tell us that the field must be supplied in order for the document to be saved successfully. [ ] indicate an array of items, and you can perform Javascript array methods on these arrays, like .push, .pop, etc. If you're familiar with Javascript, you may notice that Mongoose intuitively works with Javascript, creating a seamless experience that is also friendly to new users, making it great teaching tool.

Now that you have a very basic schema, you should be able to add it to your database and view it by installing a UI such as Robo 3T.

Have fun playing with this by making and manipulating data! Thanks for reading!

Latest comments (0)