write custom validation in mongoose

Solutions on MaxInterview for write custom validation in mongoose by the best coders in the world

showing results for - "write custom validation in mongoose"
Oscar
01 Mar 2019
1const schema = new Schema({
2  name: {
3    type: String,
4    required: true
5  }
6});
7const Cat = db.model('Cat', schema);
8
9// This cat has no name :(
10const cat = new Cat();
11cat.save(function(error) {
12  assert.equal(error.errors['name'].message,
13    'Path `name` is required.');
14
15  error = cat.validateSync();
16  assert.equal(error.errors['name'].message,
17    'Path `name` is required.');
18});
Lohan
18 Jan 2018
1const breakfastSchema = new Schema({
2  eggs: {
3    type: Number,
4    min: [6, 'Too few eggs'],
5    max: 12
6  },
7  bacon: {
8    type: Number,
9    required: [true, 'Why no bacon?']
10  },
11  drink: {
12    type: String,
13    enum: ['Coffee', 'Tea'],
14    required: function() {
15      return this.bacon > 3;
16    }
17  }
18});
19const Breakfast = db.model('Breakfast', breakfastSchema);
20
21const badBreakfast = new Breakfast({
22  eggs: 2,
23  bacon: 0,
24  drink: 'Milk'
25});
26let error = badBreakfast.validateSync();
27assert.equal(error.errors['eggs'].message,
28  'Too few eggs');
29assert.ok(!error.errors['bacon']);
30assert.equal(error.errors['drink'].message,
31  '`Milk` is not a valid enum value for path `drink`.');
32
33badBreakfast.bacon = 5;
34badBreakfast.drink = null;
35
36error = badBreakfast.validateSync();
37assert.equal(error.errors['drink'].message, 'Path `drink` is required.');
38
39badBreakfast.bacon = null;
40error = badBreakfast.validateSync();
41assert.equal(error.errors['bacon'].message, 'Why no bacon?');