英文:
Mongoose Post request still works when a required field is missing
问题
以下是您要翻译的内容:
我有一个用户模型,看起来像这样:
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const userSchema = new Schema({
fullName: {
type: String,
require: true
},
email: {
type: String,
require: true
}
})
module.exports = mongoose.model('User', userSchema)
接下来,我的控制器函数如下所示:
exports.register = (req, res) => {
const email = req.body.email
const name = req.body.fullName
bcrypt
.hash(password, 12)
.then(hashedPassword => {
const user = new User({
email: email,
password: hashedPassword,
name: name
})
return user.save()
})
.then(createdUser => {
res.status(201).json({ message: "user created", userData: createdUser })
})
.catch(err => {
if(!err.statusCode) {
err.statusCode = 500
}
next(err)
})
}
然而,当我在Postman中创建用户时,即使fullName字段是必需的,如果payload中不存在fullName字段,也不会引发错误。
payload:
{
"email": "john@example.com",
"number": "119299928",
"password": "加密的密码",
"status": "active",
"role": "administrator"
}
我希望如果字段是必需的,如果用户实际上被创建,会引发异常。我有遗漏什么吗?
<details>
<summary>英文:</summary>
I have a user model which looks like this:
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const userSchema = new Schema({
fullName: {
type: String,
require: true
},
email: {
type: String,
require: true
}
})
module.exports = mongoose.model('User', userSchema)
Moving forward, my controller function looks like this:
exports.register = (req, res) => {
const email = req.body.email
const name = req.body.fullName
bcrypt
.hash(password, 12)
.then(hashedPassword => {
const user = new User({
email: email,
password: hashedPassword,
name: name
})
return user.save()
})
.then(createdUser => {
res.status(201).json({ message: "user creared", userData: createdUser })
})
.catch(err => {
if(!err.statusCode) {
err.statusCode = 500
}
next(err)
})
}
However, when I go to Postman and create the user, even though the fullName field is required, no error is thrown if the fullName field does not exist in the payload.
payload:
{
"email": "john@example.com",
"number": "119299928",
"password": "encrypted password",
"status": "active",
"role": "administrator"
}
I would expect an exception to be thrown if a field is required, but the user actually gets created.
Am I missing anything?
</details>
# 答案1
**得分**: 1
尝试将 `require: true` 更改为模式声明中的 `required: true`。
<details>
<summary>英文:</summary>
Try changing `require: true`, to `required: true`, at the schema delcaration.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论