我的 Node.js 应用程序未检测猫鼬方法 findByIdAndDelete 作为函数

My Node.js app is not detecting the mongoose method findByIdAndDelete as a function

提问人:Samuel Becerra Posada 提问时间:11/18/2023 更新时间:11/18/2023 访问量:37

问:

感谢您抽出宝贵时间阅读本文。

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

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

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

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;

但它抛给我这个错误:

错误

请帮帮我,提前谢谢你

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

节点 .js 后端 猫鼬架构

评论

0赞 pierpy 11/18/2023
嗨,使用图像进行代码/错误会导致许多问题。请阅读为什么我不应该上传代码/数据/错误的图像?。谢谢

答:

1赞 jQueeny 11/18/2023 #1

您可以改用 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'
      });
   }
});

编辑

您还需要在架构定义中使用关键字:new

const categoriaEsquema = new mongoose.Schema({
   //...
});