【发布时间】: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 数组products 和totalPrice 的对象
我需要我的 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