0

At the moment I am generating unique UUID's and save them as a string in MongoDB. Is there a way to store these UUID's as ObjectID in MongoDB.

The problem is that User.findOne based on _id doesn't work because UUID is a string and not a ObjectID

mariodelta
  • 53
  • 6

2 Answers2

0

you don't have to generate the uuids of entities mongoose do it for you, for example if you use the create() method without passing the _id it will generate it.

it's sure better to hand-generate it.

and its by default.

Marco Bertelli
  • 343
  • 1
  • 9
  • Yes, I know that mongoose automatically generates the _id, but I want to have a UUID which looks like this c4ea5454-af54-4d9a-afa7-705b46dfe8ed. The function generates this kind of id but saves it as a string. I want to convert that string to a objectID – mariodelta Dec 06 '21 at 10:29
  • yeah change the schema type to objectId, and when save it use Type.ObjectId(YOUR_UUID4) but i think that will crash because is not the rigth format, however you can try save it as string and query not using findById but findOne – Marco Bertelli Dec 06 '21 at 10:32
  • Unfortunately, that didn't work. I still get the conversion error between a string and objectid. – mariodelta Dec 08 '21 at 09:43
0

So basically store them as _id: UUID("5fe6075a-8157-4dfc-8aab-3316ea9cbf17") format instead of string. Then it should work as expected with findOne(). Also you may refer to this answer.

fractal397
  • 534
  • 1
  • 5
  • 11