Mongoose Validators

JS
S
JavaScript

Simple validation example. Requirements: Mongoose 4

1// ./models/item.model.ts
2import * as mongoose from 'mongoose'
3
4const options = {
5    strict: false
6};
7
8const itemSchema = new mongoose.Schema({
9    name: String,
10    description: String,
11    category: String,
12    estvalue: Number
13},options)
14
15const Item = mongoose.model('Item', itemSchema)
16
17// Custom Inline Validators
18Item.schema.path('estvalue').validate((value) => {
19    return value > 0;
20}, 'Estimated value must be greather than 0');
21
22export { Item };
23
24
25
26
27// router/api/index.ts
28import { Item } from '../models/item.model'
29export default function (app) {
30
31  const forceValidatorsOptions = {
32    runValidators: true
33  };
34
35  // update by id
36  app.put('/api/item/:id', function (req, res) {
37    Item.findOneAndUpdate({_id: req.params.id}, req.body, forceValidatorsOptions, function(err) {
38      if (err) { return console.error(err) }
39      res.sendStatus(200)
40    })
41  })
42}

Created on 1/7/2018