如何使用节点js和mongodb实现joi验证器

时间:2019-04-23 10:19:47

标签: node.js joi

我尝试使用nodejs和mongodb进行Crud操作。它工作正常,但是如何使用joi验证程序验证数据。我不知道如何在连接mongodb的节点js中添加joi验证代码。

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

  });

1 个答案:

答案 0 :(得分:0)

验证快递请求正文的示例:

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