【问题标题】:Collect id in to array将 id 收集到数组中
【发布时间】:2019-08-21 19:45:02
【问题描述】:

我在 mongoDB 中有一个带有对象的数组。在数组销售中,我有 id 数组 products 和 totalPrice 的对象,我需要我的 node.js 服务器返回带有销售 id 的数组。

     {
        "_id": "5d5d066d3d20a50424211e59",
        "sales": [
            {
                "products": [
                    {
                        "_id": "5d5d066d3d20a50424211e5d",
                        "name": "dsdad",
                        "count": 2,
                        "price": 33.5
                    }
                ],
                "_id": "5d5d066d3d20a50424211e5c",
                "totalPrice": 327.4
            },
            {
                "products": [
                    {
                        "_id": "5d5d066d3d20a50424211e5b",
                        "name": "asda",
                        "count": 3,
                        "price": 324
                    }
                ],
                "_id": "5d5d066d3d20a50424211e5a",
                "totalPrice": 22.4
            }
        ],
        "date": 1566400515,
        "status": true
    }
...
]

在数组sales 中我有id 数组productstotalPrice 的对象 我需要我的 node.js 服务器返回带有销售 ID 的数组。

更新。 sales 中的每个对象都有 ID。我需要具有此 ID 的数组。像这样:

{ "_id": "5d5d066d3d20a50424211e5c"},
{"_id": "5d5d066d3d20a50424211e5a"}
]```

【问题讨论】:

  • sales = sales.map(s => s["_id"])
  • 你有什么尝试吗?
  • 另外,对于发帖人——你能举出预期输出的例子吗?就像我说的,sales 是一个数组,所以我们不能在其中放置 _id 属性....您希望它们只是销售数组中的纯字符串吗?
  • @MauriceNino 哦,老天,你是对的......由于某种原因,我完全读错了,哈哈。谢谢指正。所以它会给我一个只有“_id”属性的数组,如果那是他想要的,你就完美了。
  • db.collection.aggregate([ { "$addFields": { "sales": { "$map": { "input": "$sales", "in": { "_id": "$$this._id" } } } } } ])

标签: javascript node.js mongodb mongoose


【解决方案1】:

只需使用map() 像这样转换您的数据:

let data = 
[
  {
    "_id": "5d5d066d3d20a50424211e59",
    "sales": [
      {
        "products": [
          {
            "_id": "5d5d066d3d20a50424211e5d",
            "name": "dsdad",
            "count": 2,
            "price": 33.5
          }
        ],
        "_id": "5d5d066d3d20a50424211e5c",
        "totalPrice": 327.4
      },
      {
        "products": [
          {
            "_id": "5d5d066d3d20a50424211e5b",
            "name": "asda",
            "count": 3,
            "price": 324
          }
        ],
        "_id": "5d5d066d3d20a50424211e5a",
        "totalPrice": 22.4
      }
    ],
    "date": 1566400515,
    "status": true
  }
];

// Loop over all your items in your data array
data.forEach(d => {
  // Transform each array of sales to an array of ids of sales
  d.sales = d.sales.map(s => s["_id"]);
});

console.log(data);

【讨论】:

    【解决方案2】:

    const result = [
      {
        _id: '5d5d066d3d20a50424211e59',
        sales: [
          {
            products: [
              {
                _id: '5d5d066d3d20a50424211e5d',
                name: 'dsdad',
                count: 2,
                price: 33.5,
              },
            ],
            _id: '5d5d066d3d20a50424211e5c',
            totalPrice: 327.4,
          },
          {
            products: [
              {
                _id: '5d5d066d3d20a50424211e5b',
                name: 'asda',
                count: 3,
                price: 324,
              },
            ],
            _id: '5d5d066d3d20a50424211e5a',
            totalPrice: 22.4,
          },
        ],
        date: 1566400515,
        status: true,
      },
    ];
    
    result.forEach((r) => {
      const reference = r;
      if (reference.sales && Array.isArray(reference.sales)) {
        reference.sales = reference.sales.map((m) => { return m._id; });
      }
    });
    
    console.log(result);

    【讨论】:

    • 为什么const reference = r这个?它有什么好处?另外检查元素是否为数组的原因是什么?
    • 当您在代码中配置 ESLint 时,它不允许更改该变量 (r),如果您尝试它会发出警告 no-parm-reassign,这就是为什么我获取一个新变量 (reference ) 并对其进行更改,间接地在 r 中进行更改,因为我们直接将其分配给 const reference = r; ;
    【解决方案3】:

    在等待从查询中获取文档后,而不是运行 map 为什么不使用聚合管道这样做:

    db.collection.aggregate([
      {
        $project: {
          date: 1,
          status: 1,
          sales: {
            $map: {
              input: "$sales",
              as: "item",
              in: "$$item._id"
            }
          }
        }
      }
    ])
    

    【讨论】:

    • 销售和产品有 _id's 表示它们来自不同的集合。
    • 你确定吗?如果产品是嵌入的对象数组怎么办?
    • 我不确定,但嵌入的对象包括提到的 mongo-Id
    • 即使你创建了一个嵌入的对象数组,在保存 mongo 的对象中,如果没有设置 _id:false,总是生成 _id 用于索引
    【解决方案4】:

    您可以使用或导入 lodash 并使用下面的代码将返回销售的 id。

    let _ = require('lodash');
    let data = [
    {
    _id: '5d5d066d3d20a50424211e59',
    sales: [
      {
        products: [
          {
            _id: '5d5d066d3d20a50424211e5d',
            name: 'dsdad',
            count: 2,
            price: 33.5,
          },
        ],
        _id: '5d5d066d3d20a50424211e5c',
        totalPrice: 327.4,
      },
      {
        products: [
          {
            _id: '5d5d066d3d20a50424211e5b',
            name: 'asda',
            count: 3,
            price: 324,
          },
        ],
        _id: '5d5d066d3d20a50424211e5a',
        totalPrice: 22.4,
      },
      ],
       date: 1566400515,
        status: true
      },
     ];
    
    
    let ids = _.map(data,(d)=>{
     return _.map(d.sales, (saleItem) => {return saleItem._id;});
    })
    

    【讨论】:

    • 我知道地图。但对我来说更好的是,如果响应将只有 ids
    • 所以您只需要来自数据库查询的 id?因为这将操纵结果并仅返回 id 数组。
    猜你喜欢
    • 2022-11-19
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    相关资源
    最近更新 更多