Debug School

rakesh kumar
rakesh kumar

Posted on

How to use default value validation in node js

In Node.js and MongoDB, you can implement default value validation using a combination of the model, controller, and route components. Default value validation allows you to set default values for fields in your model schema and ensure that these default values are applied when creating new documents. Let's walk through an example to illustrate the process:

Model:
Assuming we have a "User" model, we can define default values for certain fields in the model schema. Open the file where the model is defined and add the default property to the field definition. Here's an example:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  role: {
    type: String,
    default: 'user'
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  // Other fields in the schema
});

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

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

In the example above, we've set default values for the "role" and "createdAt" fields. The default property specifies the default value to be applied if the field is not provided during document creation. In this case, the "role" field defaults to 'user', and the "createdAt" field defaults to the current date and time.

Controller:
In the controller file, which handles the logic for creating users, you can use the model to create new documents. Here's an example:

const User = require('../models/user');

// Create a new user
const createUser = async (req, res) => {
  try {
    const newUser = new User(req.body);
    await newUser.save();
    res.status(201).json(newUser);
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
};

module.exports = {
  createUser,
  // Other controller functions
};
Enter fullscreen mode Exit fullscreen mode

In the example, we create a new user by instantiating the User model with the request body, which typically contains the data for creating the user. The default values specified in the model schema will be applied if the corresponding fields are not provided in the request body.

Route:
In the route file, you define the endpoint for creating a user and connect it to the corresponding controller function. Here's an example:

const express = require('express');
const router = express.Router();
const userController = require('../controllers/user');

// Create a new user
router.post('/users', userController.createUser);

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

In the example, we define a POST route /users that maps to the createUser function in the user controller.

When a request is made to create a new user, if the "role" and "createdAt" fields are not provided in the request body, the default values specified in the model schema will be used. If the fields are provided, the provided values will be used instead.

Default value validation allows you to ensure that certain fields in your documents always have a value, even if the client doesn't explicitly provide one. This can simplify the creation process and provide consistent data across your collection.

==============================================================

Image description

Image description

Image description

Image description

Top comments (0)