Home > Software design >  Mongoose min number validation doesn't work while inserting data
Mongoose min number validation doesn't work while inserting data

Time:10-24

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.

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}`);
    }
});

CodePudding user response:

you need to deal with phone number as a string, and you can just use minLength validator there min validator for number is referring to the minimum value, not the minimum digits number, so if you can 3334445555 phone number then it's greater than 10 then it will be inserted instead you can do this

 phone: {
    type: String,
    required: true,
    minLength: [10, 'Phone number should contain at least ten digits!'],
    trim: true
},

CodePudding user response:

To my experience, you'd rather change type of phone number from Number into String, because phone number might come from input form in frontend. We don't need any calculation with phone number in future, so better to set it up as String type.

phone: {
        type: String,
        required: true,
        minLength: [10, 'Phone number should contain at least ten digits!'],
        trim: true
    },
  • Related