I have an API with Nodejs and Mongo, and I want to validate with Express-validator module if the document is owned by Signin user or not.
I want to do that by Midelware, and getting a String for know what is the collection I need to query.
programacionRouter.js
const { Router } = require('express');
const { check } = require('express-validator');
router.get('/:id', [
validarJWT,
check('id', 'No es un ID válido').isMongoId(),
// Here I want a custom MIDELWARE like -> isOwener('Users')
], obtenerProgramacion);
Where I put a comment I want a custom MIDELWARE like -> isOwener('Users'). If I pass Users query Users Mongodb table, and if i pass recipes I want to query Recipes table.
And here the controller: programacionController.js
const { handleHttpError } = require('../helpers/handleError');
const { Programacion } = require('../models');
exports.obtenerProgramacion = async (req, res) => {
try {
const { id } = req.params;
// I want to do this as a Midelware -->
// 1. Check if ID exist in this Collection
// 2. Check if this collection is Owned by User logged
const programacion = await Programacion.find({ semana: id, usuario: req.usuario._id });
// No se encuentra la reunión o no pertenece al usuario
if (programacion == '') {
return res.json({ msg: 'No existe ninguna reunión con esa ID' });
}
res.json({
msg: 'Programación cargada correctamente',
programacion
});
} catch (e) {
console.log(e);
handleHttpError(res, 'ERROR_OBTENER_PROGRAMACION', 400);
}
};
See comments in the code. I want to do two checks as a Midelware. // 1. Check if ID exist in this Collection (function for all collections) // 2. Check if this collection is Owned by User logged
Is this possible with express-validator?
Added question Really I need to do a Midelware for this validation or it's the same if I only return my document by user._id? Like:
const query = { estado: true, usuario: req.usuario._id };