當我將資料添加到我的 db mongoose 時,不會驗證我在 Schema 上定義的資料型別:
架構:
const mongoose = require("mongoose");
const Postschema = new mongoose.Schema({
nome: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true
},
morada: {
type: String,
required: true,
trim: true
}
});
const Post = mongoose.model('Post', Postschema);
module.exports = Post
功能:
const store = (req, res) => {
const post = new Post({ nome: req.body.nome, email: req.body.email, morada: req.body.morada });
post.save().then((post) => {
res.status(201).json(post)
}).catch((e) => res.status(500).json(e))
}
因此,即使我嘗試使用數字而不是字串(如下所示)創建和存盤檔案,即使在我定義它必須是架構中的字串并且物件以 wring 型別存盤后,它仍然可以作業資料。
{
"nome": 1,
"email":"Associado",
"morada":"[email protected]"
}
如您所見, nome 應該是一個字串,但我可以將它作為整數添加到我的資料庫中。我究竟做錯了什么?
uj5u.com熱心網友回復:
在這種情況下,nome 來自的欄位body被解釋為字串并Post創建檔案。
如果您需要驗證發布請求,您應該使用該express-validator庫并定義一個自定義中間件來處理正文欄位:
- 定義一個
validator.js中間件:
const { body } = require('express-validator');
const validate = (method) => {
switch (method) {
case 'store': {
return [
body('nome')
.not()
.isEmpty()
.withMessage('Nome is required')
.not()
.isNumeric()
.withMessage('Nome should be a string')
.trim()
.escape(),
body('email')
.not()
.isEmpty()
.withMessage('E-mail is required')
.isEmail()
.withMessage('Insert a valid e-mail')
.normalizeEmail(),
body('morada')
.not()
.isEmpty()
.withMessage('Morada is required')
.trim()
.escape(),
];
}
default:
break;
}
};
module.exports = { validate };
- 將該
validate函式store作為中間件添加到方法定義中:
const { validate } = require('./validator')
// Express router setup...
router.post('/url/to/post/store', validate('store'), store)
- 您可以
store通過訪問validationResult函式來處理函式中的驗證錯誤。如果出現錯誤,它將回傳一個非空集。
const { validationResult } = require('express-validator');
const store = (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
...
};
uj5u.com熱心網友回復:
您將 nome 定義為字串,但您將 nome 作為整數插入
{
"nome": 1,
"email":"Associado",
"morada":"[email protected]"
}
你應該發送資料如下
{
"nome": "1",
"email":"Associado",
"morada":"[email protected]"
}
或在插入之前將名稱轉換為字串
const post = new Post({ nome: req.body.nome.toString(), email: req.body.email, morada: req.body.morada });
或者,如果您想另存nome為數字,請更改您的名稱模式型別為Number這樣
nome: {
type: Number,
required: true,
trim: true
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/349213.html
