DEV Community

Cover image for MongoDB with Mongoose for Beginners
Christine Garaudy
Christine Garaudy

Posted on

MongoDB with Mongoose for Beginners

What is MongoDB?

A NoSQL "document database with the scalability and flexibility that you want with the querying and indexing that you need," according to the docs at www.mongodb.com. You can run it on the cloud with MongoDB Atlas, or on the server of your choice. It's designed to be simple for developers to learn to use while still being powerful enough to handle the complex requirements of large-scale applications. It stores data in JSON-like document objects that are malleable and easy to work with. It's open-source and free for anyone to use! With MongoDB, you manipulate data through object-oriented APIs rather than having to learn a special query language with SQL, which makes it more familiar and easier to understand for someone like me with no prior database management knowledge, but some general JavaScript know-how.

What is Mongoose?

Besides the adorable and vicious fuzzy African snake-killers, Mongoose is an Object Data Modeling (ODM) library for managing data that works with MongoDB and Node.js. MongoDB is schema-less, which is liberating but potentially messy, so Mongoose helps to enforce a document data structure that makes it easier to store and manipulate information. The library comes with many built-in helper functions that allow us to quickly and easily perform basic CRUD operations (create, read, update, and delete.)

How do we use them together?

First you'll need to either install MongoDB on your server with these docs: https://docs.mongodb.com/guides/server/install/ or on https://www.mongodb.com/cloud/atlas if you want to float around in their cloud. Now we'll install Mongoose in the terminal

$ npm install mongoose

You're going to have to require mongoose in the project and connect it to the database you're going to make. I'm running a server on my local machine.

const mongoose = require('mongoose');
const DB_NAME = 'catSchema';
const DB_URI = `mongodb://localhost/${DB_NAME}`;

mongoose.connect(DB_URI, { useNewUrlParser: true, autoIndex: true })
  .then(() => console.log('Connected to database'))
  .catch(err => console.error('Failed to connect to database', err));

Here, I've included success and error messages so I can be sure I'm properly linked up.

Let's make a Mongoose schema to organize our data,

const mongoose = require('mongoose');
const catSchema = new mongoose.Schema({ 
  name: String, 
  breed: String, 
});

then use the model method to CREATE it

module.exports = mongoose.model("Cat", catSchema);

Best practice with Mongoose is to split up models into their own separate files, so in a new file we can require the Cat model and use it to make a new cat. Mongoose will let us write promises, so let's do it that way to keep the code nice

const Cat = require("./models/Cat");

function saveCat(cat) {
  const c = new Cat(cat);
  return c.save();
}

saveCat({
  name: 'Fluffykins',
  breed: 'Persian'
})
  .then(doc => {
    console.log(doc);
  })
  .catch(error => {
    console.error(error);
  });

Now that we have something in there, we want to use another built-in Mongoose method to get stuff out of the database, aka READ with find() or findOne(). FindOne() will return the first document to match your query, while find() will return an array of all documents that match. If you don't specify a query, find() will return an array containing all of the documents in the collection.

const fluffy = await Cat.findOne({ name: "Fluffykins" });
//returns first Fluffykins object

const cats = await Cat.find({ name: "Fluffykins" });
//returns all Fluffykins objects in an array

const cats = await Cat.find();
//returns all cat objects in an array

We can UPDATE our cat with her favorite toys and then save it.

const fluffy = await Cat.findOne({ name: 'Fluffkins' });
fluffy.toys = ['mousie', 'catnip ball', 'string'];
const doc = await fluffy.save();
console.log(doc)
/*
 * {
 * toys: ['mousie', 'catnip ball', 'string'],
 * _id: 59e8tsdf726e5n87y92hf6234o
 * name: 'Fluffykins',
 * breed: 'Persian',
 * }
/*

(MongoDB will also assign a unique id to your entries.)

Finally, you can DELETE with the remove() method

const fluffy = await Cat.findOne({ name: 'Fluffykins' });
const goodbye = await fluffy.remove();



Conclusion

Learning how to work with the back-end can be challenging. It's more difficult to conceptualize the work being done with servers and databases in the beginning, compared to tweaking elements on the front-end and being able to immediately see the changes on the page. However, if we want to be able to create any real-world applications that will be useful to other people, we must learn how to manipulate and persist data. Mongoose helps us do just that with its handy, easy to read methods.

Oldest comments (1)

Collapse
 
d_positive_core profile image
Jai

Crisply written article. Just my thought:Always quote the references (documentation) so that readers can refer them.