mongoose模式中的数字类型始终保存为字符串

时间:2015-10-23 14:28:58

标签: node.js mongodb validation express mongoose

我有这个简单的架构,联系人为Number数据类型。奇怪的是,输入数据(联系人)总是在mongodb中保存为字符串。我不知道背景中发生了什么,或者我错过了什么。

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

在我的路线文件中,我发送用户数据以便像这样添加到数据库中

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
}

正如你所看到的,req.body.contact是用户在表单中输入的内容,我就是这样传递的。

问题是,要么我不了解实际的概念,要么我必须要做更多的事情。 注意:我没有使用任何快速或猫鼬验证器中间件。

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

您可以针对正则表达式测试联系人值。以下示例显示了使用正则表达式对10位数进行验证的自定义验证程序。通过传递 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());