Murat Colyaran
Murat Colyaran

Reputation: 2189

Converting MongoDB ObjectID to a valid id

I'm trying to fetch a document from MongoDB like this:

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

And this is 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. 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?

Edit:

I can't convert result.feedId object to string with result.feedId.toString().

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:

I don't have any idea why this has happened but id array in the result.feedId is what was I'm looking for. When I tried to convert that hex I got the _id

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

Upvotes: 1

Views: 934

Answers (2)

IAmDranged
IAmDranged

Reputation: 3020

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?

Upvotes: 1

Ujjwal
Ujjwal

Reputation: 138

Your result.feedId is an object but _id should not be object and instead it should be string as the error you posted suggests. Try changing what you pass as an _id.

Upvotes: 1

Related Questions