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
2
Answers
When you specify:
You are creating a default export. So to import the model, you would do:
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:The controller file you shared also does this for
registrazione
.as montioned in @Montgomery Watts answer either you export and import like this :
or :
Note : either you missed
cellulare
peroperty in the model or you have put it by mistake here :also : you should use
findOne
with themodel
not with theinstance
: