mongoose put 不检查必填字段

发布于 2025-01-18 14:12:48 字数 2546 浏览 0 评论 0原文

我正在制作Nodejs API,并且有一个用户模型。需要一些字段。当触发帖子发布时,它会告诉我需要一些字段,因此不会保存,但是当我使用put时,即使验证是错误的,它也会替换它,或者即使有必要的字段并且丢失了,但是副本运行好的。

这是用户的模型,

const mongoose = require('mongoose');
const validator = require('validator');

const userSchema = mongoose.Schema({

        _id: mongoose.Schema.Types.ObjectId,

        firstName: {
                type: String,
                required: [true, 'the firstName is missing'],
                validate: [(val) => validator.isAlpha(val, ['fr-FR']), 'not valid first name'],
        },
        lastName: {
                type: String,
                required: [true, 'the lastName is missing'],
                validate: [(val) => validator.isAlpha(val, ['fr-FR']), 'not valid last name'],
        },
        phoneNumber: {
                type: String,
                required: [true, 'the phoneNumber is missing'],
                unique: [true, 'phoneNumber already in use'],
                validate: [(val) => validator.isMobilePhone(val,['ar-DZ']), 'not valid phone number'],
        },
        email : {
                type: String,
                required: [true, 'the email is missing'],
                unique: [true, 'email already in use'],
                validate: [validator.isEmail, 'not valid email'],
        },
        role: {
                type : String,
                "enum" : ['teacher', 'student'],
                required : [true, 'the user `s role is missing'],
        }
});

module.exports = mongoose.model('User', userSchema);

这是我处理放置的地方

const express = require('express');
const router = express.Router();

const mongoose = require('mongoose');

const User = require('../../../../models/user');

router.put('/', (req, res) => {

        //get the new user object
        const userId = req.body.userId;
        User.replaceOne({
                _id: userId
        },
                {
                        _id: userId,
                        firstName: req.body.firstName,
                        lastName: req.body.lastName,
                        phoneNumber: req.body.phoneNumber,
                        email: req.body.email,
                        role: req.body.role
                })
        .exec()
        .then(response => {
                res.status(200).json(response);
        })
        .catch(err => console.log(err));
});

module.exports = router;

,所以我试图通过邮递员来测试这些模型,我想从Mongoose中自动执行此操作,我考虑将其分开并重定向到删除然后发布,但是我需要做首先检查,或者只是手动进行检查,并且由于使用api,我不想使用补丁方法结尾。

I am making nodejs API and I have a user model. Some fields are required. When trigger post it will tell me that some fields required so no save will be done, but when I do it with put it will replace it even if validation is wrong, or even if there is a required field and is missing, but duplicates run good.

this is the model of user

const mongoose = require('mongoose');
const validator = require('validator');

const userSchema = mongoose.Schema({

        _id: mongoose.Schema.Types.ObjectId,

        firstName: {
                type: String,
                required: [true, 'the firstName is missing'],
                validate: [(val) => validator.isAlpha(val, ['fr-FR']), 'not valid first name'],
        },
        lastName: {
                type: String,
                required: [true, 'the lastName is missing'],
                validate: [(val) => validator.isAlpha(val, ['fr-FR']), 'not valid last name'],
        },
        phoneNumber: {
                type: String,
                required: [true, 'the phoneNumber is missing'],
                unique: [true, 'phoneNumber already in use'],
                validate: [(val) => validator.isMobilePhone(val,['ar-DZ']), 'not valid phone number'],
        },
        email : {
                type: String,
                required: [true, 'the email is missing'],
                unique: [true, 'email already in use'],
                validate: [validator.isEmail, 'not valid email'],
        },
        role: {
                type : String,
                "enum" : ['teacher', 'student'],
                required : [true, 'the user `s role is missing'],
        }
});

module.exports = mongoose.model('User', userSchema);

this is where I handle put

const express = require('express');
const router = express.Router();

const mongoose = require('mongoose');

const User = require('../../../../models/user');

router.put('/', (req, res) => {

        //get the new user object
        const userId = req.body.userId;
        User.replaceOne({
                _id: userId
        },
                {
                        _id: userId,
                        firstName: req.body.firstName,
                        lastName: req.body.lastName,
                        phoneNumber: req.body.phoneNumber,
                        email: req.body.email,
                        role: req.body.role
                })
        .exec()
        .then(response => {
                res.status(200).json(response);
        })
        .catch(err => console.log(err));
});

module.exports = router;

so I tried to test those, by postman, I wanted from mongoose to do that automatically, I thought about splitting it and redirect it to delete then post, but i will need to do the checking first, or just do the checking manually, and because am using api, I don't want to use the patch method so I don't track the user for what changes he did in the front end.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月光色 2025-01-25 14:12:48

您可以,而不是replaceOne()使用UpdateOne()或 findOneAneAndupDate()带有打开验证器(默认情况下),像这样:

User.updateOne({_id: userId},
               {
                   _id: userId,
                   firstName: req.body.firstName,
                   lastName: req.body.lastName,
                   phoneNumber: req.body.phoneNumber,
                   email: req.body.email,
                   role: req.body.role
               },
               {runValidators: true})
.then(response => {
    res.status(200).json(response);
 })
 .catch(err => console.log(err));

或者您可以在模型的新实例上调用validate(),如果它有效,请继续使用更新逻辑,例如,

let user = new User({_id: userId,
                   firstName: req.body.firstName,
                   lastName: req.body.lastName,
                   phoneNumber: req.body.phoneNumber,
                   email: req.body.email,
                   role: req.body.role});
user.validate()
.then(() => {
    // update logic
})
.catch((err) => {
    // handle error
})

带有更新的蒙古验证

You can, instead of replaceOne() use updateOne() or findOneAndUpdate() with turned on validators (as they are of by default), like so:

User.updateOne({_id: userId},
               {
                   _id: userId,
                   firstName: req.body.firstName,
                   lastName: req.body.lastName,
                   phoneNumber: req.body.phoneNumber,
                   email: req.body.email,
                   role: req.body.role
               },
               {runValidators: true})
.then(response => {
    res.status(200).json(response);
 })
 .catch(err => console.log(err));

Or you can call the validate() on the new instance of the model and if it is valid continue with update logic, e.g.

let user = new User({_id: userId,
                   firstName: req.body.firstName,
                   lastName: req.body.lastName,
                   phoneNumber: req.body.phoneNumber,
                   email: req.body.email,
                   role: req.body.role});
user.validate()
.then(() => {
    // update logic
})
.catch((err) => {
    // handle error
})

Look for more information on Mongoose validation with update.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文