首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongoose: ValidatorError:路径为必填项

Mongoose: ValidatorError:路径为必填项
EN

Stack Overflow用户
提问于 2021-05-15 01:42:59
回答 1查看 226关注 0票数 0

我尝试在MongoDB中使用Mongoose进行注册,我得到了这个错误,这可能与我保存在集合中的数据类型有关,这会产生这种冲突。

错误

代码语言:javascript
复制
Error: User validation failed: name: Cast to string failed for value "{...}" at path "name", surname: Path `surname` is required., email: Path `email` is required., birth: Path `birth` is required., password: Path `password` is required.

和我的方案

代码语言:javascript
复制
const mongoose = require('mongoose');
const { Schema, model } = mongoose;
const AutoIncrement = require('mongoose-sequence')(mongoose);
const userSchema = new Schema(
    {
        name: {
            type: String,
            required: 'Please enter your name',
            unique: true,
            trim: true
        },
        surname:{
            type:String,
            required: true,
            trim: true
        },
        email:{
            type:String,
            required: true,
        },
        birth:{
            type:Date,
            required: true  
        },
        password:{
            type:String,
            required: true,
        }
    }, {
        timestamps: true
    }
);
userSchema.plugin(AutoIncrement, {id:'order_seq',inc_field: 'order'});
module.exports = model('User', userSchema);

这就是我执行查询的地方,该错误使我了解到集合并不接受所有字段

代码语言:javascript
复制
const userCtrl = {};

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

userCtrl.createUser = async (req, res) => {
    console.log(req.body);
    try {
        const { username } = req.body;
        console.log(username);
        const newUser = new User({
            name:req.body.name,
            surname:req.body.surname,
            email:req.body.email,
            birth:req.body.birth,
            password:req.body.password,
        });
        await newUser.save();
        res.json('User created');
    } catch (e) {
        console.log(e)
        res.json(e.errmsg);
    }
};
EN

回答 1

Stack Overflow用户

发布于 2021-05-29 22:07:28

正如错误所说,您没有发布任何数据,这就是为什么这意味着您的req.body对象很可能没有姓氏、电子邮件、出生和密码。

并且您已经将它们指定为Schema中的“必填”字段。这意味着如果字段为空,mongoose将不会创建用户。除非您指定了默认值。

代码语言:javascript
复制
surname: Path `surname` is required., email: Path `email` is required., birth: Path `birth` is required., password: Path `password` is required.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67538761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档