This is how I connected to the database
const dbConnection = async() => {
try {
await mongoose.connect(process.env.MONGODB_CNN);
console.log('Base de datos online');
} catch (error) {
console.log(error);
throw new Error('Error al inicializar la base de datos');
}
the problem comes when updating
const usuariosPut = (req = request, res = response) => {
const {id} = req.params;
const {password, google, correo, ...resto} = req.body;
if (password) {
const salt = bcryptjs.genSaltSync();
resto.password = bcryptjs.hashSync(password, salt);
}
const usuario = new Usuario.findByIdAndUpdate(id, resto);
res.json({
msg: 'put API - controlador',
id
});
I get that error, it would be very helpful since I just started
CodePudding user response:
Because you are trying to create a new instance of the model model rather than directly calling the method on the model.
const usuario = new Usuario.findByIdAndUpdate(id, resto);
should be:
const usuario = await Usuario.findByIdAndUpdate(id, resto);
Additionally, I don't see any async
keyword or Promise.then()
in your code. Model methods are asyncronous, so make sure to mark your main function async
like this:
const usuariosPut = async (req = request, res = response) => {
CodePudding user response:
Did you created Usuario
model before? If so, you do not need to call model constructor with new
keyword, your code should look like this:
const usuario = await Usuario.findByIdAndUpdate(id, resto);