3

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);
        }
      })();

  });
mujjiga
  • 16,186
  • 2
  • 33
  • 51
smith hari
  • 437
  • 1
  • 11
  • 22

1 Answers1

2

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
Ilarion Halushka
  • 2,083
  • 18
  • 13
  • Can you give me for how to add joi code in my code can you give me suggestion. – smith hari Apr 23 '19 at 11:52
  • Please look closely at the code I provided there is `router.post('/', validateRequest(validationSchema), async (req, res) => // rest of your code goes here` – Ilarion Halushka Apr 23 '19 at 11:55
  • I have one more doubt also .I tried to get the data in mongodb using node js.but I got only one data.its throwing error for Can't set headers after they are sent.I tried many ways .but I still facting this issue.how to solve this issue any suggestion – smith hari Apr 23 '19 at 12:59
  • my db code let r = await db.collection('Ecommerce').find(); r.forEach(function(result,err) { res.send(result) }) – smith hari Apr 23 '19 at 13:01
  • could you create a new question with code and error stack and then give me the link to new question – Ilarion Halushka Apr 23 '19 at 13:01
  • https://stackoverflow.com/questions/55812098/i-tried-crud-operation-using-nodejs-and-mongodb-all-crud-operation-is-working-f – smith hari Apr 23 '19 at 13:14