简体   繁体   English

将 MongoDB ObjectID 转换为有效 id

[英]Converting MongoDB ObjectID to a valid id

I'm trying to fetch a document from MongoDB like this:我正在尝试从 MongoDB 获取文档,如下所示:

let document = await db.collection('administration').findOne({ _id: result.feedId });

And this is result.feedId :这是result.feedId

{
     _bsontype: 'ObjectID',
     id: Uint8Array(12) [
     96, 129, 130, 179, 211,
     203, 136,  42, 149, 106,
     68,  49
     ]
} 

However, while trying to do that I'm getting an error like this:但是,在尝试这样做时,我遇到了这样的错误:

Error: object [{"_bsontype":"ObjectID","id":{"0":96,"1":129,"2":130,"3":179,"4":211,"5":203,"6":136,"7":42,"8":149,"9":106,"10":68,"11":49}}] is not a valid ObjectId

As far as I know, if _id is bson type then I don't need to convert it to ObjectId.据我所知,如果_id是 bson 类型,那么我不需要将其转换为 ObjectId。 However, I get such an error when I did not convert it.但是,当我没有转换它时,我得到了这样的错误。

When I try to convert it, I get an error like this:当我尝试转换它时,我收到如下错误:

const { ObjectID } = require('mongodb');
let document = await db.collection('administration').findOne({ _id: ObjectID( result.feedId )});
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

How can I convert convert/fix that result.feedId to a valid id?如何将转换/修复该result.feedId转换为有效 ID?

Edit:编辑:

I can't convert result.feedId object to string with result.feedId.toString() .我无法使用result.feedId.toString()result.feedId object 转换为字符串。

When I try to do that, I'm getting a result like this:当我尝试这样做时,我得到这样的结果:

// console.log(result.feedId.toString());
[object Object]
//console.log(JSON.stringify(result.feedId.toString()));
"[object Object]"

Edit 2:编辑2:

I don't have any idea why this has happened but id array in the result.feedId is what was I'm looking for.我不知道为什么会发生这种情况,但result.feedId中的id数组是我正在寻找的。 When I tried to convert that hex I got the _id当我尝试转换该十六进制时,我得到了_id

const id = Buffer.from(result.feedId.id).toString('hex');

Your result.feedId is an object but _id should not be object and instead it should be string as the error you posted suggests.您的 result.feedId 是 object 但 _id 不应该是 object 而应该是字符串,因为您发布的错误提示。 Try changing what you pass as an _id.尝试更改您作为 _id 传递的内容。

Isn't the error:是不是错误:

Error: object [{"_bsontype":"ObjectID","id":{"0":96,"1":129,"2":130,"3":179,"4":211,"5":203,"6":136,"7":42,"8":149,"9":106,"10":68,"11":49}}] is not a valid ObjectId

saying that the issue is that result.feedId is actually an array containing the ObjectID you're interested in?说问题在于result.feedId实际上是一个包含您感兴趣的ObjectID的数组?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM