Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Using Node, Express and Mongoose, I'm trying to insert data into MongoDB through a POST method. The fields I'm trying to insert has a phone field on which I'm trying to assign a validation that will check if it has minimum ten digits. Otherwise, it'll throw validation error message. While inserting the data, it is being saved even though the phone field has less than ten digits. Why is this happening? And how to solve it? Please be advised, it is happening in case of inserting a data to MongoDB.

What I have tried:

Here's the Mongoose model:
const mongoose = require('mongoose');
const validator = require('validator');

const schema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minLength: [2, 'Name should contain at least two characters!'],
        trim: true
    },
    email: {
        type: String,
        required: true,
        trim: true,
        validate(value) {
            if (!validator.isEmail(value))
                throw new Error('Invalid email!');
        }
    },
    phone: {
        type: Number,
        required: true,
        min: [10, 'Phone number should contain at least ten digits!'],
        trim: true
    },
    message: {
        type: String,
        required: true,
        minLength: [3, 'Message should contain at least three characters!'],
        trim: true
    },
    date: {
        type: Date,
        required: true,
        default: Date.now
    }
});


const RdwMessage = new mongoose.model('RdwMessage', schema);
module.exports = RdwMessage;


Here's the route to insert the data through POST:
app.post('/contact', async (req, res) => {
    try {
        const doc = new RdwMessage(req.body);
        await doc.save();
        res.status(201).render('index');
    } catch (error) {
        res.status(404).send(`Failed to submit message with the following error: ${error}`);
    }
});
Posted
Updated 23-Oct-22 6:17am

1 solution

You have defined phone as a Number with a minimum value of 10. If you want to validate the number of digits then it needs to be a String. See Mongoose v6.6.7: Validation[^].
 
Share this answer
 
Comments
priyamtheone 24-Oct-22 5:18am    
I understand. min on a number field checks for the value itself and not the number of digits. Thanks for pointing it out.
Richard MacCutchan 24-Oct-22 5:33am    
It was easy to find in the documentation.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900