Error while creating user

Asked

Viewed 87 times

-1

I am having the following error when trying to create a user in my api

Validationerror: address.0.status: Path estado is required. , Address.0.city: Path cidade is required. , address.0.neighborhood: Path bairro is required. , address.0.street: Path logradouro is required. , address.1.cep: Path cep is required. , address.1.city: Path cidade is required. , address.1.neighborhood: Path bairro is required. , address1.street: Path logradouro is required. , address2.status: Path estado is required. , address.2.cep: Path cep is required. , address.2.neighborhood: Path bairro is required. , address.2.street address: Path logradouro is required. , address3.status: Path estado is required. , address3.cep: Path cep is required. , address.3.city: Path cidade is required. , Address.3.district: Path bairro is required. , address.4.status: Path estado is required. , address.4.cep: Path cep is required. , city address.4.: Path cidade is required. , address.4.street address: Path logradouro is required.

I have the following code in the user model:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcryptjs');

const UserSchema = new Schema({
    email: { type: String, required: true, unique: true, lowercase: true },
    senha: {type: String, required: true, select: false},
    nome: {type: String, required: true, select: true},
    sobrenome: {type: String, required: true, select: true},
    cpf: {type: String, required: true, select: true, unique: true,},
    endereco: [{
        logradouro: {type: String, required: true, select: true},
        bairro: {type: String, required: true, select: true},
        cidade: {type: String, required: true, select: true},
        cep: {type: String, required: true, select: true},
        estado: {type: String, required: true, select: true},
    }],
    created: {type: Date, default: Date.now}
});

UserSchema.pre('save', function (next) {
    let user = this;
    if(!user.isModified('senha')) return next();
    bcrypt.hash(user.senha, 10, (err,encrypted) => {
        user.senha = encrypted;
        return next();
    });
});


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

and the following user controller code:

const bcrypt = require('bcryptjs');
const mongoose = require('mongoose');
const Users = require('../models/user');
const jwt = require('jsonwebtoken');

const createUserToken = (userId) => {
    return jwt.sign({id: userId}, 'chavesecreta', {expiresIn: '7d'});
}

module.exports = {


    buscar(req, res) {
        Users.find({}, (err, data) => {
            if (err) return res.send({ error: 'Erro na consulta de usuarios!' });
            return res.send(data);
        });
    },
    criar(req, res) {
        const { email, senha, nome, sobrenome, cpf } = req.body;
        if (!email || !senha || !nome || !sobrenome || !cpf ) return res.send({ error: "Dados não preenchidos!" });
        Users.findOne({ email: email }, (err, data) => {
            if (err) return res.send({ error: "Erro ao buscar usuario!" });
            if (data) return res.send({ error: "Usuario já registrado!" });

            Users.create(req.body, (err, data) => {
                if (err) return res.send({ error: "Erro ao criar usuario!" + err });
                data.senha = undefined;
                return res.send({data, token: createUserToken(data.id)});
            });
        });
    },
    auth(req, res) {
        const { email, senha } = req.body;
        if (!email || !senha) return res.send({ error: "Preencha todos os campos!" });
        Users.findOne({ email: email }, (err, data) => {
            if (err) return res.send({ error: "Erro ao buscar usuario!" });
            if (!data) return res.send({ error: "Usuario não registrado!" });
            bcrypt.compare(senha, data.senha, (err, same) => {
                if (!same) return res.send({ error: "Senha incorreta!" });
                data.senha = undefined;
                return res.send({data, token: createUserToken(data.id)});
            })
        }).select('+senha');
    },
    validacao(req, res) {
        return res.send({status: "Valido"});
    }
}

How can I fix this error? Thanks in advance

  • Staff who decline questions could at least state the reason

1 answer

0


After a lot of headache I started reading the documentation of Mongoose and the error was in the model where I have to change:

const UserSchema = new Schema({
    email: { type: String, required: true, unique: true, lowercase: true },
    senha: {type: String, required: true, select: false},
    nome: {type: String, required: true, select: true},
    sobrenome: {type: String, required: true, select: true},
    cpf: {type: String, required: true, select: true, unique: true,},
    endereco: [{
        logradouro: {type: String, required: true, select: true},
        bairro: {type: String, required: true, select: true},
        cidade: {type: String, required: true, select: true},
        cep: {type: String, required: true, select: true},
        estado: {type: String, required: true, select: true},
    }],
    created: {type: Date, default: Date.now}
});

To:

const UserSchema = new Schema({
    email: { type: String, required: true, unique: true, lowercase: true },
    senha: {type: String, required: true, select: false},
    nome: {type: String, required: true, select: true},
    sobrenome: {type: String, required: true, select: true},
    cpf: {type: String, required: true, select: true, unique: true,},
    endereco: {
        logradouro: {type: String, required: true, select: true, default: undefined},
        bairro: {type: String, required: true, select: true, default: undefined},
        cidade: {type: String, required: true, select: true, default: undefined},
        cep: {type: String, required: true, select: true, default: undefined},
        estado: {type: String, required: true, select: true, default: undefined},
    },
    created: {type: Date, default: Date.now}
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.