Thanks for taking the time to read this.
I have an schema defined like this,
const mongoose = require('mongoose');
//modelo de categorias
const categoriaEsquema = mongoose.Schema({
nombre: {
type: String,
required: true
},
color: {
type: String,
},
icono: {
type: String,
},
/*imagen: {
type: String,
required: true
},*/ //Aún no se usa
})
exports.CategoriaModelo = mongoose.model('Categoria',categoriaEsquema);
And I am trying to achieve a DELETE request with the following code in other page
const {CategoriaModelo} = require('../modelos/categorias');
const express = require('express');
const router = express.Router();
router.delete('/:id', (req, res) => {
CategoriaModelo.findByIdAndRemove(req.params.id);
});
module.exports = router;
But it throws me this error:
Please help me, thank you in advance
I tried using other methods like finOneAnd... etc, but it seems like it is not detecting Mongoose methods at all.
You can use findByIdAndDelete instead and await the asynchronous call like so:
router.delete('/:id', async (req, res) => { //< Mark callback as async
try{
const deletedDoc = await CategoriaModelo.findByIdAndDelete(req.params.id);
return res.status(200).json({
message: 'Delete was a success'
})
}catch(err){
console.log(err);
//Handle error
return res.status(400).json({
message: 'Error on server'
});
}
});
Edit:
You also need to use the new
keyword in your schema definition:
const categoriaEsquema = new mongoose.Schema({
//...
});