Jay
Jay

Reputation: 782

Number type in mongoose schema always get saved as string

I have this simple schema, with contact as Number data type. Strangely, the input data(contact) always gets saved as string in mongodb. I have no idea, as to what is happening in the background, or am I missing something.

var mongoose = require('mongoose');
var memberSchema = new mongoose.Schema({
.
. Other fields are not shown/ necessary 
.
contact: {
   type: Number,
   required: true,
   }
});

module.exports = mongoose.model('Member',memberSchema);

In my routes file, I send user data for adding into DB like this

exports.post = function(req,res,next){
    if(!req.body.name || !req.body.email || !req.body.contact)
        return res.render('index', {error: 'Fill Name, Email and Contact'});
    //req.body.contact = parseInt(req.body.contact);
    var member = {
        name: req.body.name,
        email: req.body.email,
        contact: req.body.contact
}

As you can see req.body.contact is whatever user has entered in a form and I pass it that way.

The problem is, either I am not understanding the actual concept or there must me something more to it. Note: I am not using any express or mongoose validator middlewares.

Any help would be highly appreciated.

Upvotes: 4

Views: 15542

Answers (1)

chridam
chridam

Reputation: 103365

You could test the contact value against a regular expression. The following example shows a custom validator using a regular expression to validates against a 10 digit number. Custom validation is declared by passing a validation function:

var memberSchema = new Schema({
    contact: {
        type: Number,
        validate: {
            validator: function(v) {
                return /d{10}/.test(v);
            },
            message: '{VALUE} is not a valid 10 digit number!'
        }
    }
});

var Member = mongoose.model('Member', memberSchema);

var m = new Member();

m.contact = '123456789';
// Prints "ValidationError: 123456789 is not a valid 10 digit number!"
console.log(m.validateSync().toString());

m.contact = 0123456789;
// Prints undefined - validation succeeded!
console.log(m.validateSync());

Upvotes: 2

Related Questions