One of the core concepts of Mongoose is that it enforces a schema on top of a schema-less design such as MongoDB. In doing so, we gain a number of new features, including built-in validation. By default, every schema type has a built-in required validator available. Furthermore, numbers have both min and max validators and strings have enumeration and matching validators.
Last active
April 18, 2016 21:52
-
-
Save crguezl/82caad653fc2483b9d5b623536060eb0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
"use strict"; | |
const util = require('util'); | |
const assert = require('assert'); | |
const mongoose = require('mongoose'); | |
mongoose.connect('mongodb://localhost/tutu'); | |
const breakfastSchema = new mongoose.Schema({ | |
eggs: { | |
type: Number, | |
min: [6, 'Too few eggs'], | |
max: 12 | |
}, | |
bacon: { | |
type: Number, | |
required: [true, 'Why no bacon?'] | |
}, | |
drink: { | |
type: String, | |
enum: ['Coffee', 'Tea'] | |
} | |
}); | |
const Breakfast = mongoose.model('Breakfast', breakfastSchema); | |
let badBreakfast = new Breakfast({ | |
eggs: 2, | |
bacon: 0, | |
drink: 'Milk' | |
}); | |
let error = badBreakfast.validateSync(); | |
console.log(error); | |
assert.equal(error.errors['eggs'].message, | |
'Too few eggs'); | |
assert.ok(!error.errors['bacon']); | |
assert.equal(error.errors['drink'].message, | |
'`Milk` is not a valid enum value for path `drink`.'); | |
badBreakfast.bacon = null; | |
error = badBreakfast.validateSync(); | |
assert.equal(error.errors['bacon'].message, 'Why no bacon?'); | |
mongoose.connection.close(); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
const util = require('util'); | |
const assert = require('assert'); | |
const mongoose = require('mongoose'); | |
mongoose.connect('mongodb://localhost/tutu'); | |
var toySchema = new mongoose.Schema({ | |
color: String, | |
name: String | |
}); | |
var Toy = mongoose.model('Toy', toySchema); | |
var validator = function (value) { | |
return /blue|green|white|red|orange|periwinkle/i.test(value); | |
}; | |
Toy.schema.path('color').validate(validator, | |
'Color `{VALUE}` not valid', 'Invalid color'); | |
var toy = new Toy({ color: 'grease'}); | |
toy.save(function (err) { | |
// err is our ValidationError object | |
// err.errors.color is a ValidatorError object | |
console.log(err); | |
assert.equal(err.errors.color.message, 'Color `grease` not valid'); | |
assert.equal(err.errors.color.kind, 'Invalid color'); | |
assert.equal(err.errors.color.path, 'color'); | |
assert.equal(err.errors.color.value, 'grease'); | |
assert.equal(err.name, 'ValidationError'); | |
mongoose.connection.close(); | |
}); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
"use strict"; | |
const util = require('util'); | |
const mongoose = require('mongoose'); | |
mongoose.connect('mongodb://localhost/tutu'); | |
const ScoreSchema = mongoose.Schema({ | |
"name" : { type: String, required: true }, | |
"cal" : { type: Number, required: true, min: 0, max: 10 } | |
}); | |
const Score = mongoose.model("Score", ScoreSchema); | |
Score.remove().then( () => { | |
let c = [ new Score({"name":"Juana", "cal":10 }), | |
new Score({"name":"Pedro", "cal":3 }), | |
new Score({"name":"Maria", "cal":5 }), | |
new Score({"name":"Antonio", "cal":12 })]; | |
let p = []; | |
c.forEach( (n, i) => { | |
p[i] = n.save(function (err) { | |
if (err) { console.log(`Hubieron errores salvando ${n}:\n${err}`); return err; } | |
}); | |
}); | |
let p5 = Promise.all(p).then( (value) => { | |
let query = Score.find({cal: {$lte: 10, $gte: 5}}); | |
query.select('name cal'); | |
query.exec((err, notas) => { | |
if (err) { console.log("ERROR: " + err); } | |
let c = 1; | |
notas.forEach(function (nota) { | |
console.log (`${c++}: ${nota.name} of ${nota.cal}`); | |
}); | |
}).then( function() { mongoose.connection.close(); } ); | |
}, | |
(err) => { | |
console.log(`Grrr!!! Ocurrieron errores! <${err}>`); | |
mongoose.connection.close(); | |
} | |
); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment