Skip to content

Instantly share code, notes, and snippets.

@stongo stongo/app.js
Last active May 24, 2019

Embed
What would you like to do?
Joi validation in a Mongoose model
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', function() {
return console.error.bind(console, 'connection error: ');
});
db.once('open', function() {
var User;
return User = require('./user.js');
});
// Validate a user
(function() {
var User = require('./user.js');
var me = { username: 'foo' };
var user = new User(me);
var err = user.joiValidate(me);
if (err) throw err;
user.save(function(err, saved) {
...
});
})();
var userSchema = mongoose.Schema({
username: String,
password: String,
email: String,
first_name: String,
last_name: String,
created: { type: Date, default: Date.now },
});
userSchema.methods.joiValidate = function(obj) {
var Joi = require('joi');
var schema = {
username: Joi.types.String().min(6).max(30).required(),
password: Joi.types.String().min(8).max(30).regex(/[a-zA-Z0-9]{3,30}/).required(),
email: Joi.types.String().email().required(),
first_name: Joi.types.String().required(),
last_name: Joi.types.String().required(),
created: Joi.types.Date(),
}
return Joi.validate(obj, schema);
}
module.exports = mongoose.model('User', userSchema);
@dhavaljardosh

This comment has been minimized.

Copy link

commented Jul 23, 2018

Spend 4 days to understand Joi with Mongoose, even tried Joigoose (it had several limitations) and finally found this. This is very clear. Thank you very much.

@JeffLabonte

This comment has been minimized.

Copy link

commented Aug 3, 2018

Good thinking! Good job! Thank you for sharing!

@sagar-gavhane

This comment has been minimized.

Copy link

commented Aug 5, 2018

Combination of Joi and Mongoose is great...

@meteorlxy

This comment has been minimized.

Copy link

commented Aug 20, 2018

userSchema.statics.joiValidate = ...

Could be another choice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.