Mongoose Schema验证不起作用

时间:2018-03-21 13:17:37

标签: node.js mongodb mongoose

这是我的模型文件。我想在架构上创建验证,但这对我不起作用。我不知道为什么,因为这是标准的实施。如果我错了,建议我,任何人。

'use strict';
var mongoose = require('mongoose');

var UserSchema = mongoose.Schema({
    username: {
        type: String,
        lowercase: true// My value is not converted into lowercase
    }
});

var User = module.exports = mongoose.model('User', UserSchema, 'User');

router.post('/putname, function(req, res){
  var user = new User({
    username: req.body.username
  });
  user.save(function(err, data){
    if(error) { console.log(error) }
    else { console.log('Entry Inserted Successfully') }
  });
});

1 个答案:

答案 0 :(得分:1)

new之前您遗失了mongoose.Schema。并且您只能在mongoose.model

中包含参数
'use strict';
var mongoose = require('mongoose');

var UserSchema = new mongoose.Schema({
    username: {
        type: String,
        lowercase: true 
    }
});

var User = module.exports = mongoose.model('User', UserSchema);

router.post('/putname, function(req, res){
  var user = new User({
    username: req.body.username
  });
  user.save(function(err, data){
    if(error) { console.log(error) }
    else { console.log('Entry Inserted Successfully') }
  });
});

您还可以将代码组织为:

'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({ ... });