Home > Blockchain >  TypeError: Utente is not a constructor
TypeError: Utente is not a constructor

Time:02-02

I'm trying to do a user registration with a Node js app and MongoDB but I have this error: const utente = new Utente({ ||||| TypeError: Utente is not a constructor

There's my model utente.js

const mongoose = require("mongoose");

const Utente = mongoose.model(
  "Utente",
  new mongoose.Schema({
    email: String,
    nome: String,
    cognome: String,
    password: String,
    admin: String,
  })
);

module.exports = Utente;

There's the controller for the registration:

const { validationResult } = require("express-validator");
const { Utente } = require("../models/utente");

exports.registrazione = async (request, response, next) => {
  const errors = validationResult(request);
  if (!errors.isEmpty()) {
    return response.status(422).json({
      message: "Errore nell'Inserimento dei Dati",
      error: errors.array(),
    });
  }

  console.log("Email:", request.body.email);

  const utente = new Utente({
      email: request.body.email,
      nome: request.body.nome,
      cognome: request.body.cognome,
      password: request.body.password,
      cellulare: request.body.cellulare,
      admin: request.body.admin
  });
  
  if (utente.findOne({email: request.body.email})) {
    return response.status(400).send('Esiste già un account con questa email');
  } else {
      utente.save();

      response.status(201).json({
        messages: "Utente Registrato con Successo",
      });
  }
};

I tried to display the information with console.log()from the request and the information are showed correctly but I got this error

CodePudding user response:

When you specify:

module.exports = Utente;

You are creating a default export. So to import the model, you would do:

const Utente = require("../models/utente");

Notice that Utente is not surrounded by { }.

If you do want to import Utente the way you are currently, you would export it like this:

exports.Utente = Utente;

The controller file you shared also does this for registrazione.

CodePudding user response:

as montioned in @Montgomery Watts answer either you export and import like this :

module.exports = Utente;
const Utente = require("../models/utente");

or :

module.exports = {Utente};
const {Utente} = require("../models/utente");

Note : either you missed cellulare peroperty in the model or you have put it by mistake here :

const utente = new Utente({
  email: request.body.email,
  nome: request.body.nome,
  cognome: request.body.cognome,
  password: request.body.password,
  cellulare: request.body.cellulare,
  admin: request.body.admin
});

also : you should use findOne with the model not with the instance :

Utente.findOne({email: request.body.email})) // Utente with uppercase U
  • Related