Setting Up MongoDB with Express.js

Tutorial 1 of 5

Introduction

Welcome to this MongoDB and Express.js tutorial! Our goal is to set up a MongoDB database and connect it to an Express.js application. This can be achieved using a MongoDB driver or an Object Data Modeling (ODM) tool like Mongoose.

By the end of this tutorial, you will:

  • Understand how MongoDB and Express.js interact
  • Be able to set up a MongoDB database
  • Connect your Express.js application to your MongoDB database using Mongoose

Prerequisites:

  • Basic knowledge of JavaScript
  • Familiarity with Node.js and Express.js
  • MongoDB and Node.js installed on your computer

Step-by-Step Guide

1. Install Mongoose

We will be using Mongoose for this tutorial, an ODM tool that helps in managing relationships between data, provides schema validation, and translates between objects in code and the representation of those objects in MongoDB.

npm install mongoose

2. Connect MongoDB with Express.js

First, start your MongoDB server. Then, in your Express.js app, require mongoose and connect to your MongoDB database.

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_database', {useNewUrlParser: true, useUnifiedTopology: true});

mongodb://localhost/my_database is the path where your MongoDB server is running.

3. Create a Schema and a Model

Schemas are the structure of the document within the collection, they are a powerful way to enforce structure on the data. Models are higher-order constructors that take a schema and create an instance of a document.

const Schema = mongoose.Schema;

const UserSchema = new Schema({
  name: String,
  email: String,
  password: String
});

const User = mongoose.model('User', UserSchema);

4. Using the Model

You can now use the User model to create, read, update, and delete users in your MongoDB database.

// Create a new user
let user = new User({ name: 'John', email: 'john@example.com', password: '123456' });
user.save();

// Find a user
User.find({name: 'John'}, function(err, users) {
  console.log(users);
});

Code Examples

Example 1: Creating a User

Here's how you create a new user in MongoDB using Mongoose:

let user = new User({ name: 'John', email: 'john@example.com', password: '123456' });
user.save(function (err, user) {
  if (err) return console.error(err);
  console.log("User saved successfully!");
});

This code creates a new instance of the User model and saves it to the database. If there's an error, it logs that error. Otherwise, it logs a success message.

Example 2: Finding a User

Here's how you find a user:

User.find({ name: 'John' }, function(err, user) {
  if (err) return console.error(err);
  console.log(user);
});

This code uses the find method on the User model to find a user with the name 'John'. If there's an error, it logs that error. Otherwise, it logs the user.


Summary

In this tutorial, we've learned how to connect a MongoDB database with an Express.js application using Mongoose. We've also learned how to create and find users in MongoDB using Mongoose.

Next steps would include diving deeper into Mongoose and learning about more advanced features such as middleware, validation, and more complex queries.

For further reading, the Mongoose documentation is a great resource!


Practice Exercises

  1. Create a new user: Create a new user in your MongoDB database with a different name and email than the user we created in the tutorial.

  2. Find a user: Find the user you just created in your MongoDB database.

  3. Update a user: Update the name of the user you just created.

Solutions:

  1. Here's how you might create a new user:
let user = new User({ name: 'Jane', email: 'jane@example.com', password: '654321' });
user.save(function (err, user) {
  if (err) return console.error(err);
  console.log("User saved successfully!");
});
  1. Here's how you might find the user you just created:
User.find({ name: 'Jane' }, function(err, user) {
  if (err) return console.error(err);
  console.log(user);
});
  1. Here's how you might update the name of the user you just created:
User.updateOne({ name: 'Jane' }, { name: 'Janet' }, function(err, res) {
  if (err) return console.error(err);
  console.log(res);
});

Keep practicing with different queries and different models to improve your MongoDB and Mongoose skills!