smith hari
smith hari

Reputation: 437

how to implement joi validator using node js and mongodb

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

Answers (1)

Ilarion Halushka
Ilarion Halushka

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

Related Questions