Michael Koska
Michael Koska

Reputation: 43

Using Mongo ObjectId as an Index

I am trying to iterate over an array retrieved from a Model.find() call.

const lists = ListModel.find();

const listSet = lists.reduce<Record<string, Set<string>>>((acc, list) => {
   const listId = list._id;

   acc[listId] = new Set()

   return acc;
}, {});

The listId is new ObjectId(1234qwer1234qwer) and the error is Type 'ObjectId' cannot be used as an index type. What is the ideal way to handle this? I will likely want to use the objectId reference at some point shortly after.

Edit: I have tried using list.id instead of list._id but had an error of Type 'Buffer' cannot be used as an index type.

Upvotes: 1

Views: 306

Answers (1)

asportnoy
asportnoy

Reputation: 2534

Update:

You can use ._id.toString() to get the stringified version of the ID, which you should be able to use as an index.

Original Answer

You can use .id instead of ._id to get the stringified version of the ID, which you should be able to use as an index.

Upvotes: 2

Related Questions