如何在使用猫鼬findone时删除数组元素

时间:2020-09-13 18:15:23

标签: mongoose

我有以下代码。图像是一个数组,我希望输出除图像内存在的Path以外的所有内容。如何实现? 图片包含-ID,标题,路径

 if (dbRes !== null) {
            res.apiSuccess({
              
                town: dbRes.town,
                county: dbRes.county,
                postCode: dbRes.postCode,
                image: dbRes.image
  });
        } else {
            res.apiError(messages.product.not_found);
        }

这是输出的屏幕截图:

enter image description here

2 个答案:

答案 0 :(得分:1)

更新:OP共享了一个对象,该对象显示了更改响应遍历的每个参数的定义。

您可以使用mongoose内置函数将dbres转换为对象。然后只需使用delete命令从图像中删除属性,然后再在响应中传递它即可。

根据上述响应,我们假设dbRes是包含属性image,town,country和postCode的对象数组。图像也是对象的数组。

     if (!dbRes) {
        // Convert db res to object and destructure attributes
        const dataArr = dbRes.toObject(); // Array of objects
        const response = dataArr.map((data) => {
           const {
              town,
              county,
              postCode,
              image = [] // Add default so that we don't have to check for null/undefined
           } = data;
           
           const newImageArr = image.map((imageData) => {
                // Delete path attribute from image object
                delete imageData.path;
                return imageData;  
           });

           return {
              town,
              county,
              postCode,
              image: newImageArr,
           }
        });
        
        res.apiSuccess(response);
    } else {
        res.apiError(messages.product.not_found);
    }

资源:

Mongoose toObject Docs

Object Destructuring Tutorial

数据库级别忽略

所有这些,如果您在发送响应之前根本不需要使用path变量,则只需在数据库级别将其忽略即可。这样,您就不需要遍历对象。在这篇文章中查看猫鼬的选择功能 https://stackoverflow.com/a/24348603/14167216

答案 1 :(得分:1)

您可以使用dot notation和mongodb projectionspath数组中排除images字段。

db.collection.findOne({
    _id: dataId
}, {
    "image.path": 0
})

以下查询假定文档具有一个_id字段,并且在第一级具有一个images数组。该查询将返回整个文档,仅排除path数组中的images字段