'Mongoose - get all requried fields only from the schema
I want to apply validation on controller level similar to what we have in a Form Request in Laravel but I want that in Node JS. I want to know the required fields from the mongoose model so that I can apply the required rule for that field here.
Ofcourse, the userModel.schema.tree returns all the attributes of the schema, but I only need the required ones.
const validate = require('validator')
const userModel = require('../../../models/user.model');
module.exports.registerValidator = (data) => {
// required validation
console.log(data);
const modelFields = Object.keys(userModel.schema.tree);// gets all the fields
const requiredModelFields = [];// get all required fields
// format validation
if (!validate.isEmail(data.email)) {
console.log('not email');
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
