Validation Error In Visual Studio Code with MongoDB

Viewed 47

Below is the my mongodb schema Product with six fields - username, email, bio, image, hash and salt :

var mongoose = require("mongoose");
var productSchema = new mongoose.Schema(
    {
        username: {
            type: String,
            lowercase: true,
            required: [true, "can't be blank"],
            index: true,
        },
        email: {
            type: String,
            lowercase: true,
            required: [true, "can't be blank"],
            index: true,
        },
        bio: String,
        image: String,
        hash: String,
        salt: String,
    },
    { timestamps: true }
);
module.exports = mongoose.model("Product", productSchema);

My Data/Product.js Info, data stored in the database:

[
    {
        username: "USERNAME",
        email: "name.username@gmail.com",
        bio: "BIOSample",
        image: "Image",
        hash: "sample",
        salt: "sample",
    },
];

My Controller Code:

const Product = require("../models/product");

//create new product => /api/v1/product/new
exports.newProduct = async (req, res, next) => {
    const product = await Product.create(req.body);
    res.status(201).json({
        success: true,
        product,
    });
};

While npm run I get this error message as shown below:

Product validation failed: email: can't be blank, username: can't be blank.
1 Answers

If the error that you are getting is

Product validation failed: email: can't be blank, username: can't be blank.

Then probably, don't use the required as required: [true, "can't be blank"] . Maybe because of that you might get the error.

You need to just write required: true . And also you need to write your further validation for your email and username, that you can make it in the front-end if you have your code or else, write a validation function in nodejs for email and username . where it satisfies your condition.

Something like this code below, This is for you to understand:

const Joi = require("joi");
const mongoose = require("mongoose");
const { Genre, validateGenre, genreSchema } = require("./genre");
Joi.objectId = require("joi-objectid")(Joi);

const movieSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 50,
    },
    numberInStock: {
        type: Number,
        required: true,
        min: 0,
        max: 255,
        default: 13,
    },
    dailyRentalRate: {
        type: Number,
        min: 0,
        max: 255,
        required: true,
    },
    liked: {
        type: Boolean,
        default: false,
    },
    genre: {
        type: genreSchema,
        required: true,
    },
});

const Movie = mongoose.model("Movie", movieSchema);

function validateMovie(movie) {
    const schema = {
        title: Joi.string().required().min(5).max(255),
        numberInStock: Joi.number().required().min(0).max(255),
        dailyRentalRate: Joi.number().required().min(0).max(255),
        liked: Joi.boolean(),
        // genreId: Joi.string().required()
        genreId: Joi.objectId().required(),
        _id: Joi.objectId(),
    };
    return Joi.validate(movie, schema);
}

module.exports.Movie = Movie;
module.exports.validateMovie = validateMovie;

Here above I have written a validation function for movieSchema.

So same way you too can write validation function:

const Joi = require("joi");
const mongoose = require("mongoose");
Joi.objectId = require("joi-objectid")(Joi);

var productSchema = new mongoose.Schema(
    {
        username: {
            type: String,
            lowercase: true,
            required: true,
            index: true,
        },
        email: {
            type: String,
            lowercase: true,
            required: true,
            index: true,
            unique: true,
        },
        bio: String,
        image: String,
        hash: String,
        salt: String,
    },
    { timestamps: true }
);
const Product = mongoose.model("Product", productSchema);


function validateProduct(product) {
    const schema = {
        username: Joi.string().required(),
        email: Joi.string().required().email(),
        bio: Joi.string().required(),
        image: Joi.string().required(),
        hash: Joi.string().required(),
        salt: Joi.string().required(),
        _id: Joi.objectId(),
    };
    return Joi.validate(product, schema);
}

module.exports.Product = Product;
module.exports.validateProduct = validateProduct;

You need to do npm install joi for Joi to work. https://www.npmjs.com/package/joi

Related