如何使用节点 js 和 mongodb 实现 joi 验证器
how to implement joi validator using node js and mongodb
我尝试使用 nodejs 和 mongodb 进行 crud 操作。它工作正常但是如何使用 joi validator.I 验证数据不知道如何在连接 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);
}
})();
});
验证快速请求正文的示例:
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
我尝试使用 nodejs 和 mongodb 进行 crud 操作。它工作正常但是如何使用 joi validator.I 验证数据不知道如何在连接 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);
}
})();
});
验证快速请求正文的示例:
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