【问题标题】:how to remove an array element when using mongoose findone使用猫鼬findone时如何删除数组元素
【发布时间】:2020-12-31 13:43:10
【问题描述】:

我有以下代码。图像是一个数组,我希望输出除了图像中存在的路径之外的所有内容。如何实现? 图片包含 - 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);
        }

这是输出截图:

【问题讨论】:

    标签: mongoose


    【解决方案1】:

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

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

    根据上述响应,我们假设 dbRes 是一个对象数组,其中包含属性图像、城镇、县和邮政编码。而且image也是一个对象数组。

         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

    数据库级别省略

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

    【讨论】:

    • 数据输出但仍然在输出中获得路径。
    • 你能提供你所看到的吗?你是说你仍然得到路径键但未定义?还是你还拿到带数据的路径键?
    • 我正在获取城镇、国家、邮政编码和所有数组图像元素(id、标题、路径)。路径没有被删除
    • 添加了相关图片的截图
    • 哦,image 是一个数组,所以它不起作用。将更新响应
    【解决方案2】:

    您可以使用dot notation 和mongodb projectionsimages 的数组中排除path 字段。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-25
      • 2018-05-28
      • 2020-06-10
      • 2018-06-11
      • 1970-01-01
      • 2021-06-14
      • 2013-01-23
      • 2020-12-18
      相关资源
      最近更新 更多