How to connect Node.js with mongodb using mongoose? | Projectshop

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:

Perl
mkdir my-node-project
cd my-node-project
npm init -y

3. Install Dependencies: Install necessary dependencies (express, mongoose):

Bash
npm install express mongoose

4. Set up Express Server: Create an’ index.js‘ file and set up a basic Express server:

JavaScript
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:

JavaScript
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:

JavaScript
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:

JavaScript
// 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart