Sure, here’s a step-by-step guide to connect Node.js with MongoDB using Mongoose:
1. Install MongoDB: First, ensure you have MongoDB installed on your system. You can download and install it from the official MongoDB website.
2. Create a Node.js Project: Create a new directory for your project and initialize it with npm:
mkdir my-node-project
cd my-node-project
npm init -y3. Install Dependencies: Install necessary dependencies (express, mongoose):
npm install express mongoose4. Set up Express Server: Create an’ index.js‘ file and set up a basic Express server:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});5. Connect to MongoDB with Mongoose: Add code to connect to MongoDB using Mongoose in ‘index.js‘:
const mongoose = require('mongoose');
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/my_database', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.error('Error connecting to MongoDB', error);
});Replace ‘'mongodb://localhost:27017/my_database'‘ with your MongoDB connection string. Make sure MongoDB is running locally on the default port ‘27017‘.
6. Define Schema and Model: Define a schema and create a model for your MongoDB collections:
const { Schema, model } = mongoose;
// Define Schema
const userSchema = new Schema({
name: String,
email: String,
age: Number
});
// Create Model
const User = model('User', userSchema);7. Use the Model: Now, you can use the ‘User‘ model to perform CRUD operations on the MongoDB database. For example:
// Create a new user
const newUser = new User({
name: 'John Doe',
email: 'john@example.com',
age: 30
});
// Save the user to the database
newUser.save()
.then((user) => {
console.log('User saved:', user);
})
.catch((error) => {
console.error('Error saving user:', error);
});That’s it! You now have a Node.js server connected to MongoDB using Mongoose, ready to perform database operations.
