我的 Node.js 应用程序未将 mongoose 方法 findByIdAndDelete 检测为函数

问题描述 投票:0回答:1

感谢您花时间阅读本文。

我有一个像这样定义的模式,

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);

我正在尝试在其他页面中使用以下代码来实现删除请求

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;

但是它给了我这个错误:

Error

请帮助我,先谢谢你了

我尝试使用其他方法,如 finOneAnd... 等,但似乎它根本没有检测到 Mongoose 方法。

node.js mongoose backend mongoose-schema
1个回答
0
投票

您需要使用 findByIdAndDelete 并等待异步调用,如下所示:

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'
      });
   }
});
© www.soinside.com 2019 - 2024. All rights reserved.