NodeJS 为什么我的路由deleteMany在Mongoose中不起作用

w8ntj3qf  于 11个月前  发布在  Node.js
关注(0)|答案(1)|浏览(145)

我正在尝试建立一个路由来删除所有包含实体"techs":[]的对象。
我正在训练 Mongoose ,在错误发生的地方犯了一个错误,我向API发送了错误的信息。
所以,我写了代码:

router.delete("/delete", connectDatabase, async (req, res, next) => {
  try {
    const resDB = await SchemaProjects.deleteMany({ techs: [] });
    res.status(200).json({
      status: "OK",
      statusMensagem: "Projects sucefully deleted",
      response: resDB,
    });
  } catch (error) {
    res.status(500).json("internal server error");
  }
});

字符串
但它会去catch并返回:
服务器内部错误
我的API..

[
    {
        "_id": "6589873d4e3eb0cee59435dc",
        "type": "landing",
        "title": "Google Clone",
        "description": "Google Clone landinpg page",
        "techs": [],
        "imageUrl": "https://i.ibb.co/wp9mHmq/google.png",
        "__v": 0
    },
    {
        "_id": "658dc7bb77d42309479a0d79",
        "type": "landing",
        "title": "Google Clone",
        "description": "Google Clone landinpg page",
        "techs": [],
        "imageUrl": "https://i.ibb.co/wp9mHmq/google.png",
        "__v": 0
    },
    {
        "_id": "658dc7bd77d42309479a0d7b",
        "type": "landing",
        "title": "Google Clone",
        "description": "Google Clone landinpg page",
        "techs": [],
        "imageUrl": "https://i.ibb.co/wp9mHmq/google.png",
        "__v": 0
    },
    {
        "_id": "658de1f581c1748f5c5ce802",
        "type": "landing",
        "title": "Google Clone",
        "description": "Google Clone landinpg page",
        "techs": [],
        "imageUrl": "https://i.ibb.co/wp9mHmq/google.png",
        "__v": 0
    },
]


我搞不懂的是,这就是它的工作原理...

router.get("/get", connectDatabase, async (req, res, next) => {
  try {
    const resDB = await SchemaProjects.find({ techs: [] });
    res.status(200).json({
      status: "OK",
      statusMensagem: "Project sucefully deleted",
      response: resDB,
    });
  } catch (error) {
    res.status(500).json("internal server error");
  }
});


并正确返回API的数据,相同的实体和值({ techs: [] }

lhcgjxsq

lhcgjxsq1#

要删除数组为空的文档,您应该使用$size运算符来检查长度为0的数组,如下所示:

const resDB = await SchemaProjects.deleteMany({ techs: { $size: 0 } });

字符串
或者使用查询生成器语法:

const resDB = await SchemaProjects.where('techs').size(0).deleteMany();

相关问题