Validationerror: companies validation failed: county: Path `county` is required

Asked

Viewed 137 times

-1

I can’t see the mistake that keeps me from POST (store the data in the database). Also, in the form when selecting a country he should only take his cities, instead he calls all cities and consequently all municipalities. Anyone with any ideas, please help! Thank you.

Model:

const mongoose = require("mongoose")
const Schema = mongoose.Schema

const Empresa = new Schema({
    name: {
        type: String,
        required: true
    },
    slug: {
        type: String,
        required: true
    },
    county: {
        type: Schema.Types.ObjectId,
        ref: "coutries",
        required: true
    },
    city: {
        type: Schema.Types.ObjectId,
        ref: "cities",
        required: true
    },
    municipality: {
        type: Schema.Types.ObjectId,
        ref: "municipalities",
        required: true
    },
    date: {
        type: Date,
        default: Date.now()
    }
})

mongoose.model("empresas", Empresa)

Routa / GET:

router.get('/empresas/add', async function(req, res) {
    try {
      const [countries, cities, municipalities] = await Promise.all([Country.find(), City.find(), Municipality.find()]);
      res.render('ferramentas/addempresas', { countries: countries, cities: cities, municipalities: municipalities});
    } catch(err) {
      req.flash('error_msg', 'Houve um erro ao carregar o formulário');
      res.redirect('/ferramentas/empresas');
    };
});

Routa / POST:

router.post("/empresas/nova", function(req, res){

    var erros = []

    if(!req.body.name || typeof req.body.name == undefined || req.body.name == null){
        erros.push({texto: "Nome inválido"})
    }
    if(!req.body.slug || typeof req.body.slug == undefined || req.body.slug == null){
        erros.push({texto: "slug inválido"})
    }
    if(req.body.country == "0"){
        erros.push({texto: "País inválido, crie um país"})
    }
    if(req.body.city == "0"){
        erros.push({texto: "Cidade inválida, crie uma cidade"})
    }
    if(req.body.municipality == "0"){
        erros.push({texto: "Município inválido, crie antes um município"})
    }
    if(erros.length > 0){
        res.render("ferramentas/empresas", {erros: erros})
    }else{
        const novaEmpresa = {
            name: req.body.name,
            slug: req.body.slug,
            country: req.body.country,
            city: req.body.city,
            municipality: req.body.municipality
        }
        new Empresa(novaEmpresa).save().then(function(){
            req.flash("sucesso_msg", "Empresa criada com sucesso!")
            res.redirect("/ferramentas/empresas")
        }).catch(function(err){
            console.log(err)
            req.flash("error_msg", "Houve um erro ao salvar a empresas, tente novamente!")
            res.redirect("/ferramentas/empresas")
        })
    }
})

HTML:

<form action="/ferramentas/empresas/nova" method="POST">
  <div class="modal-body">
    <h6 class="card-inside-title">Nome:</h6>
    <div class="row clearfix">
      <div class="col-sm-12">
        <div class="form-group">
          <input type="text" id="name" name="name" class="form-control" placeholder="Escreva o nome do município" autocomplete="off" required/>
        </div>
      </div>
    </div>
    <h6 class="card-inside-title">Slug:</h6>
    <div class="row clearfix">
      <div class="col-sm-12">
        <div class="form-group">
          <input type="text" id="slug" name="slug" class="form-control" placeholder="Escreva o slug da município" autocomplete="off" required />
        </div>
      </div>
    </div>
    <h6 class="card-inside-title">País:</h6>
    <div class="row clearfix">
      <div class="col-sm-12">
        <div class="form-group" style="margin: 0 -18px 0 -18px">
          <select name="country" class="form-control">
            <option>Selecione o país</option>
            {{#each countries}}
            <option value="{{_id}}">{{name}}</option>
            {{else}}
            <option value="0">Sem país registrado</option>
            {{/each}}
          </select>
        </div>
      </div>
    </div>
    <h6 class="card-inside-title">Cidade:</h6>
    <div class="row clearfix">
      <div class="col-sm-12">
        <div class="form-group" style="margin: 0 -18px 0 -18px">
          <select name="city" class="form-control">
            <option>Selecione a cidade</option>
            {{#each cities}}
            <option value="{{_id}}">{{name}}</option>
            {{else}}
            <option value="0">Sem cidade registrada</option>
            {{/each}}
          </select>
        </div>
      </div>
    </div>
    <h6 class="card-inside-title">Município:</h6>
    <div class="row clearfix">
      <div class="col-sm-12">
        <div class="form-group" style="margin: 0 -18px 0 -18px">
          <select name="municipality" class="form-control">
            <option>Selecione o local</option>
            {{#each municipalities}}
            <option value="{{_id}}">{{name}}</option>
            {{else}}
            <option value="0">Sem município registrado</option>
            {{/each}}
          </select>
        </div>
      </div>
    </div>
  </div>
  <div class="modal-footer">
    <button type="submit" class="btn btn-success btn-round waves-effect">GUARDAR</button>
  </div>
</form>
  • Your URL of the POST route is /companies/new and the one you are sending the form post is /tools/companies/new are different urls, put /tools/companies/new at the post route url

  • @Anderson, you can use middleware to organize your routes. I think it’s safe to assume that a middleware redirects to this module if "tools" are at the base of the URL, there’s nothing wrong with the route.

  • I know, but I don’t see any middleware over there

  • I’m using Middleware, I just didn’t put it on this pole.

1 answer

-1

Good morning, The problem is in your Schema code. Instead of writing "country" it says "county".

Browser other questions tagged

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