How do you handle form validation, especially with nested models, in Node.js + Express + Mongoose + Jade

后端 未结 3 677
隐瞒了意图╮
隐瞒了意图╮ 2021-02-02 16:04

How are you handling form validation with Express and Mongoose? Are you using custom methods, some plugin, or the default errors array?

While I could possibly see using

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-02 16:47

    Mongoose has validation middleware. You can define validation functions for schema items individually. Nested items can be validated too. Furthermore you can define asyn validations. For more information check out the mongoose page.

    var mongoose = require('mongoose'),
        schema = mongoose.Schema,
        accountSchema = new schema({
          accountID: { type: Number, validate: [
            function(v){
              return (v !== null);
            }, 'accountID must be entered!'
          ]}
        }),
        personSchema = new schema({
          name: { type: String, validate: [
            function(v){
              return v.length < 20;
            }, 'name must be max 20 characters!']
          },
          age: Number,
          account: [accountSchema]
        }),
        connection = mongoose.createConnection('mongodb://127.0.0.1/test');
        personModel = connection.model('person', personSchema),
        accountModel = connection.model('account', accountSchema);
    
    ...
    var person = new personModel({
      name: req.body.person.name, 
      age: req.body.person.age,
      account: new accountModel({ accountID: req.body.person.account })
    });
    person.save(function(err){
      if(err) {
        console.log(err);
        req.flash('error', err);
        res.render('view');
      }
    ...
    });
    

提交回复
热议问题