0
0
Expressframework~5 mins

Mongoose ODM setup in Express

Choose your learning style9 modes available
Introduction

Mongoose helps you talk to MongoDB easily by turning data into objects you can use in your code.

When you want to save user info like names and emails in a database.
When you need to organize data with rules, like making sure emails are unique.
When you want to connect your Express app to MongoDB to store and get data.
When you want to use JavaScript objects to work with your database data.
When you want to handle database errors and validations simply.
Syntax
Express
import mongoose from 'mongoose';

mongoose.connect('mongodb://localhost:27017/mydatabase')
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error('Connection error', err));

Use mongoose.connect() with your MongoDB URL to start the connection.

The connection returns a promise, so use then and catch to handle success or errors.

Examples
This connects your app to a local MongoDB database called 'testdb'.
Express
import mongoose from 'mongoose';

// Connect to local MongoDB database named 'testdb'
mongoose.connect('mongodb://localhost:27017/testdb')
  .then(() => console.log('Connected!'))
  .catch(err => console.error('Error:', err));
Options help avoid warnings and improve connection stability.
Express
import mongoose from 'mongoose';

// Connect with options for better compatibility
mongoose.connect('mongodb://localhost:27017/myapp', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
  .then(() => console.log('Connected with options'))
  .catch(console.error);
Sample Program

This Express app connects to MongoDB using Mongoose. It logs connection status and serves a simple message on the home page.

Express
import express from 'express';
import mongoose from 'mongoose';

const app = express();
const PORT = 3000;

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

app.get('/', (req, res) => {
  res.send('Hello from Express with MongoDB!');
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
OutputSuccess
Important Notes

Make sure MongoDB is running on your machine before connecting.

Use environment variables to keep your database URL safe in real apps.

Mongoose connection is asynchronous, so handle success and errors properly.

Summary

Mongoose connects your Express app to MongoDB easily.

Use mongoose.connect() with your database URL to start.

Handle connection success and errors with promises.