nodejs logo

Connecting to MongoDB with Mongoose

Overview

Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. It provides a schema-based solution to model application data and simplifies interaction with MongoDB.

Installing Mongoose

You can install the mongoose package using npm. Run the following command:

npm install mongoose

Creating a Connection

Here's how to create a connection to your MongoDB database:

const mongoose = require('mongoose');

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/yourDatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => {
  console.log('Connected to MongoDB');
})
.catch(err => {
  console.error('Error connecting to MongoDB:', err);
});

Replace yourDatabase with the name of your actual database.

Defining a Schema

You can define a schema for your data using Mongoose:

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  age: Number
});

// Create a model
const User = mongoose.model('User', userSchema);

This schema defines a User model with three fields: name, email, and age.

Inserting Data

You can easily insert data into your MongoDB database:

const newUser = new User({
  name: 'John Doe',
  email: 'john@example.com',
  age: 30
});

// Save the user to the database
newUser.save()
  .then(() => console.log('User saved'))
  .catch(err => console.error('Error saving user:', err));

Closing the Connection

It's good practice to close the connection when you're done:

mongoose.connection.close(() => {
  console.log('Connection to MongoDB closed');
});
© 2024 MongoDB Connection Guide