Debug School

rakesh kumar
rakesh kumar

Posted on

How to use if else condition when u submit data in node js

Use of if else condition in req.body inside routing

Use of if else condition in req.body inside Controller

Use of if else condition in req.body inside routing

To use an if-else condition based on the req.body when submitting data in a Node.js MongoDB application, you can follow these steps:

First, ensure you have the necessary dependencies installed: express and mongoose. You can install them by running the command npm install express mongoose.

Set up your Node.js and Express server in a file, let's say server.js. Import the required modules and configure the server to handle requests:


const express = require('express');
const mongoose = require('mongoose');

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

// Middleware to parse JSON data
app.use(express.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// Define a route for submitting data
app.post('/submit', (req, res) => {
  // Access the data from the request body
  const data = req.body;

  // Perform your if-else condition based on the data
  if (data.name === 'John') {
    // Do something if the name is 'John'
    res.send('Hello, John!');
  } else {
    // Do something for other names
    res.send('Hello, stranger!');
  }
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

In the above example, we define a route /submit that listens for POST requests. When a POST request is made to this route, we access the submitted data from req.body. We can then perform an if-else condition based on the data received. If the name in the data is "John", we send a response saying "Hello, John!". Otherwise, we send a response saying "Hello, stranger!".

Remember to replace 'mongodb://localhost/mydatabase' with the appropriate MongoDB connection string for your database.

You can test this functionality by making a POST request to http://localhost:3000/submit with a JSON payload in the request body, like:

{
  "name": "John"
}
Enter fullscreen mode Exit fullscreen mode

The server will respond with "Hello, John!" in this case.

Another Way

To use an if-else condition based on the req.body inside a router when submitting data in a Node.js MongoDB application, you can follow these steps:

Set up your Node.js project with the required dependencies (express and mongoose). You can install them by running the command npm install express mongoose.

Create a file, let's say routes.js, to define your router and handle the routes:

// routes.js

const express = require('express');
const router = express.Router();
const Todo = require('../models/Todo');

router.post('/submit', async (req, res) => {
  const { name } = req.body;

  // Perform your if-else condition based on the data
  if (name === 'John') {
    // Do something if the name is 'John'
    res.send('Hello, John!');
  } else {
    // Do something for other names
    res.send('Hello, stranger!');
  }
});

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

Create a models directory and define a Todo model (or any other model you need) in a separate file, let's call it Todo.js:

// models/Todo.js

const mongoose = require('mongoose');

const todoSchema = new mongoose.Schema({
  // Define your schema fields here
  name: {
    type: String,
    required: true,
  },
  // ... other fields
});

module.exports = mongoose.model('Todo', todoSchema);
Enter fullscreen mode Exit fullscreen mode

In your main application file (e.g., app.js or server.js), import the router and use it:

const express = require('express');
const mongoose = require('mongoose');
const routes = require('./routes');

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

// Middleware to parse JSON data
app.use(express.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// Use the router
app.use('/', routes);

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

In the above example, we define a router that handles the /submit route. When a POST request is made to this route, we access the submitted data from req.body. We can then perform an if-else condition based on the data received. If the name in the data is "John", we send a response saying "Hello, John!". Otherwise, we send a response saying "Hello, stranger!".

Remember to replace 'mongodb://localhost/mydatabase' with the appropriate MongoDB connection string for your database.

You can test this functionality by making a POST request to http://localhost:3000/submit with a JSON payload in the request body, like:

{
  "name": "John"
}
Enter fullscreen mode Exit fullscreen mode

The server will respond with "Hello, John!" in this case.

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Use of if else condition in req.body inside Controller

To use an if-else condition based on the req.body inside a controller when submitting data in a Node.js MongoDB application, you can follow these steps:

Set up your Node.js project with the required dependencies (express and mongoose). You can install them by running the command npm install express mongoose.

Create a controller file, let's say todoController.js, to handle the logic for submitting data:

// todoController.js
const Todo = require('../models/Todo');

exports.submitData = async (req, res) => {
  const { name } = req.body;

  // Perform your if-else condition based on the data
  if (name === 'John') {
    // Do something if the name is 'John'
    res.send('Hello, John!');
  } else {
    // Do something for other names
    res.send('Hello, stranger!');
  }
};
Enter fullscreen mode Exit fullscreen mode

Create a models directory and define a Todo model (or any other model you need) in a separate file, let's call it Todo.js:

// models/Todo.js
const mongoose = require('mongoose');

const todoSchema = new mongoose.Schema({
  // Define your schema fields here
  name: {
    type: String,
    required: true,
  },
  // ... other fields
});

module.exports = mongoose.model('Todo', todoSchema);
Enter fullscreen mode Exit fullscreen mode

Create a routes file, let's say routes.js, to define your router and associate it with the controller:

// routes.js
const express = require('express');
const router = express.Router();
const todoController = require('../controllers/todoController');

router.post('/submit', todoController.submitData);

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

In your main application file (e.g., app.js or server.js), import the router and use it:

const express = require('express');
const mongoose = require('mongoose');
const routes = require('./routes');

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

// Middleware to parse JSON data
app.use(express.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
Enter fullscreen mode Exit fullscreen mode
// Use the router
app.use('/', routes);

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

In the above example, we define a controller function submitData inside todoController.js. This controller function handles the logic for submitting data. We access the submitted data from req.body and perform an if-else condition based on the data received. If the name in the data is "John", we send a response saying "Hello, John!". Otherwise, we send a response saying "Hello, stranger!".

Remember to replace 'mongodb://localhost/mydatabase' with the appropriate MongoDB connection string for your database.

You can test this functionality by making a POST request to http://localhost:3000/submit with a JSON payload in the request body, like:

{
  "name": "John"
}
Enter fullscreen mode Exit fullscreen mode

The server will respond with "Hello, John!" in this case.

Image description

Image description

Top comments (0)