Reputation: 437
I tried crud operation using nodejs and mongodb. It is working fine but how to validate data using joi validator.I do not know how to add joi validation code in node js connecting mongodb.
product.js
const Joi = require('joi');
router.post('/', async (req, res) => {
(async function() {
try {
await client.connect();
console.log("Connected correctly to server");
const db = client.db('olc_prod_db');
let r = await db.collection('Ecommerce').insertOne(req.body);
assert.equal(1, r.insertedCount);
res.send("Inserted Sucessfully")
client.close();
} catch(err) {
console.log(err.stack);
}
})();
});
Upvotes: 3
Views: 3181
Reputation: 2343
Example of validating express request body:
const Joi = require('joi');
const validateRequest = (schema) => async (req, res, next) => {
const { error } = Joi.validate(req.body, schema);
if (error) {
throw new Error(error);
}
return next();
};
const validatinSchema = Joi.object().keys({
firstName: Joi.string().required(),
lastName: Joi.string().required(),
}),
router.post('/', validateRequest(validationSchema), async (req, res) =>
// rest of your code
Upvotes: 2