【发布时间】:2015-03-28 06:37:06
【问题描述】:
聚合后我得到了这个结果。 _id 字段是每个班级的 id,我申请了 {$group:{_id:"$_id", .....
[{ _id: 54c977314f5293b74ea54f96, subject: 'math' }, score: 73.5335 },
{ _id: 54c977314f5293b74ea54f96, subject: 'science' }, score: 56.2192 },
{ _id: 54c977314f5293b74ea54f96, subject: 'history' }, score: 82.8821 },
{ _id: 54c974bdff0d993b4ecf34ce, subject: 'math' }, score: 68.2598 },
{ _id: 54c974bdff0d993b4ecf34ce, subject: 'science' }, score: 77.8712 },
{ _id: 54c974bdff0d993b4ecf34ce, subject: 'history' }, score: 71.9218 },
... ]
问题是 _id 值不是字符串类型。所以当我向客户端发送 JSON 时,它会显示格式错误的 JSON。
如何获取字符串类型_id?提前致谢。
【问题讨论】:
-
是否需要包含
_id?你在用_id做什么?您可以从输出中抑制它。 ObjectId 是 ObjectId - 它不是字符串或任何可以直接用 JSON 表示的类型,您需要决定将其表示为 JSON 类型的策略。 -
您可以使用toString()方法将_id转换为字符串,然后再发送给客户端。
标签: mongodb mongoose aggregation-framework