Reputation: 8411
I want to prevent user input to be inserted into the MongoDB. I want to validate user input properly.
Joi offers a schema based verification in order to test the user input. Actually sounds good.
Mongoose also have schemas itself, what are the differences?
How about using Joi schema and use mongojs plugin instead of Mongoose?
Upvotes: 2
Views: 2381
Reputation: 90
Mongoose's schemas: This is where you define the model and the fields it's going to accept
eg.
const Schema = require('mongoose').Schema;
const UserSchema = new Schema ({
username: String
email: String
})
const User = mongoose.module("user", UserSchema))
Here you're saying that the User model will accept only a username and an email and both are going to be strings.
Joi's schema: Here you define the validation rules to validate the received data before creating a doc of it.
eg.
const receivedData = {username: "John Doe", email: "[email protected]"}
const Joi = require('joi');
const schema = Joi.object().keys({
username: Joi.string().alphanum().min(3).max(30).required(),
email: Joi.string().email()
})
const result = Joi.validate(receivedData, schema)
So this is how you define the rules with the Joi schema
username
field must be a string, alphanum and of length between 3 and 30email
field must be a string and an emailThe result will be stored in the result
constant in a form of an object.
And I haven't used mongojs
before but Joi doesn't relay on Mongoose. so I guess it'll be fine to use monojs
.
Upvotes: 3