在mongoose中使用mongo uuid

时间:2014-11-09 19:58:25

标签: node.js mongodb mongoose

我将mongo中的_id设置为uuid via node plug in" node-uuid"当我看到robomongo中的值时,它看起来像这样

"_id" : UUID("5fe6075a-8157-4dfc-8aab-3316ea9cbf17"),

然而,当我使用mongoose检索值并将其发送到客户端时,我会收到许多奇怪的字符。

" ID":" \ u0007ZWM3 \u0016ꜿ\ u0017"

我使用的架构是

_id: {
    type: String,
    default: '',
    trim: true
},

无论如何都要做到这一点吗?

谢谢,

[R

1 个答案:

答案 0 :(得分:0)

您可以使用uuid-mongodb模块。

使用此模块,您可以将BSON UUID(猫鼬返回)转换为字符串。

因此,在您的示例中,我们假设Mongoose查询返回一个文档doc,该文档的_id字段包含BSON UUID值。要将UUID转换为字符串,可以像这样使用uuid-mongodb

const uuidString = MUUID.from(doc._id).toString();

将UUID作为字符串后,将其返回给客户端

有关更多详细信息,请转到here