MongoDB 返回 _id 字段作为 id 字符串而不是 ObjectID。

3
如何创建一个Mongo查询,使其返回_id字段作为id并进行字符串化。
给定以下代码。
const _id = new ObjectId(id)
const event = await db.collection('events').findOne({ _id })

我该如何产生这个输出

event = { id: 644289148310cef91729d97c, name: 'Event Name' }

与当前输出不同

event = { id: ObjectId("644289148310cef91729d97c"), name: 'Event Name' }

我想将此作为Mongo查询的一部分来完成,而不是在JavaScript中迭代返回的对象。
我正在使用`mongodb`库,而不是mongoose。

2
您可以使用投影 { _id: 0, id: { $convert: { input: "$_id", to: "string"} }, event: 1 } 来更改输出。 - Dhaval Gajjar
1
const event = await db.collection('events').findOne({ _id },{_id: 0, id:{$toString: "$_id"}}) - nimrod serok
1
顺便提一下,在 Node.js 驱动程序中,投影的写法类似于 findOne({ _id },{projection:{_id:0,....}}),如果我没记错的话。 - cmgchess
1个回答

3
这可以使用projection$toString实现。
const event = await db()
    .collection('events')
    .findOne(
        { _id },
        { 
            projection: {
                _id: 0,
                id: {$toString: "$_id" },
                name: 1,
            }
        }
    )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接