DEV Community

sujon554
sujon554

Posted on

3 2

Setup MongoDB in Node.js with Mongoose

Setting up database connection

npm install mongoose --save
Enter fullscreen mode Exit fullscreen mode

First let import the dependency;

const mongoose = require("mongoose");
Enter fullscreen mode Exit fullscreen mode

Then let’s store the path of the database in a variable. The path should look like the following, with and being replaced with a user you have created for the database.

const dbPath = "mongodb://<dbuser>:<dbpassword>@ds250607.mlab.com:38485/test-db";
Enter fullscreen mode Exit fullscreen mode

connect to the database.

mongoose.connect(dbPath, {
    useNewUrlParser: true,
});
Enter fullscreen mode Exit fullscreen mode
module.exports = mongoose;
Enter fullscreen mode Exit fullscreen mode

Once the application is started, it would be better if there was an indicator showing whether the application successfully connected to the database or not. So let’s add some more code to fix that.

const db = mongoose.connection;
db.on("error", () => {
    console.log("> error occurred from the database");
});
db.once("open", () => {
    console.log("> successfully opened the database");
});
Enter fullscreen mode Exit fullscreen mode

In the end the database.js should look like this.


// database.js
const mongoose = require("mongoose");
const dbPath = "mongodb://<dbuser>:<dbpassword>@ds250607.mlab.com:38485/test-db";
mongoose.connect(dbPath, {
    useNewUrlParser: true,
});
const db = mongoose.connection;
db.on("error", () => {
    console.log("> error occurred from the database");
});
db.once("open", () => {
    console.log("> successfully opened the database");
});
module.exports = mongoose;
Enter fullscreen mode Exit fullscreen mode

Setting up models/schema

// models/userModel.js
const mongoose = require("../database");
const schema = {
    name: { type: mongoose.SchemaTypes.String, required: true },
    email: { type: mongoose.SchemaTypes.String, required: true },
    password: { 
        type: mongoose.SchemaTypes.String, 
        required: true, 
        select: false
    }
};
const collectionName = "user"; // Name of the collection of documents
const userSchema = mongoose.Schema(schema);
const User = mongoose.model(collectionName, userSchema);
module.exports = User;

Enter fullscreen mode Exit fullscreen mode
// Create user
User.create({
    name: name,
    email: email,
    password: password
});
// Find user by email
User.findOne({
    email: email
});
// Find user by email with the password field included
User.findOne({
    email: email
}).select("+password");
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (1)

Collapse
 
curiousdev profile image
CuriousDev

What are the benefits of using Mongoose in general?

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay