如何删除数组中mongo对象的属性?

编程入门 行业动态 更新时间:2024-10-06 23:21:37

如何删除数<a href=https://www.elefans.com/category/jswz/34/1771283.html style=组中mongo对象的属性?"/>

如何删除数组中mongo对象的属性?

我希望下面的摘录使我的问题更加清楚。我可以获取一个嵌入了类别对象数组的对象。我只想从类别对象中显示某些属性。

所以这就是我现在得到的:

{
  "photo": [],
  "_id": "5ec55ae39eere8ert85bf8fe749",
  "title": "Blog about coding",
  "description": "Hi, I want to share with you my incredible journey as a software developer...",
  "rate": 3,
  "category": [
    {
      "_id": "5ec55ae39aaa78985f8fe74a",
      "name": "programming",
      "display_name": "Programming"
    }
  ],
  "createdAt": "2020-05-20T16:29:23.982Z",
  "updatedAt": "2020-05-20T16:29:23.982Z",
  "__v": 0
}

使用以下代码:

/* GET blog with id */
router.get("/:id", async (req, res, next) => {
    try {
        const blog = await Blog.findById(req.params.id); // How to filter out fields of objects in category array?
        res.send(blog);
    } catch(ex) {
        res.status(400).send(ex); 
    }
});

这是我真正想要的:

{
  "photo": [],
  "_id": "5ec55ae39eere8ert85bf8fe749",
  "title": "Blog about coding",
  "description": "Hi, I want to share with you my incredible journey as a software developer...",
  "rate": 3,
  "category": [
    {
      "display_name": "Programming"
    }
  ],
  "createdAt": "2020-05-20T16:29:23.982Z",
  "updatedAt": "2020-05-20T16:29:23.982Z",
  "__v": 0
}

所以,在类别中,我只需要“ display_name”

我如何得到这个。我以为以前看过解决方案,但现在找不到了。

回答如下:

由于您使用的是.findById(),它是猫鼬包装器,.findOne({_id: ObjectId()})减轻了将输入字符串转换为ObjectId()的负担,但是.find()对于投影没有太多帮助,您需要列出所有如下所示的字段:

/** .findById(inputString, projection) */

Blog.findById(req.params.id,
{
  "category.display_name": 1,
  "title": 1,
  "description": 1,
  "rate": 1,
  "createdAt": 1,
  "updatedAt": 1
})

/** Or */

Blog.findById(req.params.id,
{
  "category._id": 0,
  "category.name": 0,
})

Test:由于操场无法使用.findById,请使用.find()进行测试:mongoplayground

但是如果您倾向于使用aggregation,则可以在投影中做更多的事情:

const mongoose = require('mongoose');

/* GET blog with id */
router.get("/:id", async (req, res, next) => {
    try {
        const blog = await Blog.aggregate([{$match : {_id : mongoose.Types.ObjectId(req.params.id)}},
            { $addFields: { category: { $map: { input: "$category", in: { display_name: "$$this.display_name" } } } } }
        ]);
        res.send(blog);
    } catch(ex) {
        res.status(400).send(ex); 
    }
});

Test: mongoplayground

注:此聚合查询遍历category数组,并且在每个对象中仅保留display_name。仅当需要在category对象中排除很多字段时,才使用此管道。我建议在.findById()中使用第二个选项,因为您无需将string转换为ObjectId()和聚合管道就可以排除类别数组对象内的字段name_id

更多推荐

如何删除数组中mongo对象的属性?

本文发布于:2024-05-07 21:42:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1757384.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   属性   对象   mongo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!