Is it ok to use Mongo's “Object ID” as its unique identifier? If so, how can I convert it to a string and look it up by string?

前端 未结 3 1641
清歌不尽
清歌不尽 2021-01-07 18:30

For example...

user/view/?id=324gijsdfi3h25o1

I can str() it...but...

How can I find it up by string?

3条回答
  •  孤独总比滥情好
    2021-01-07 18:56

    ObjectId is a handy way of generating a unique _id, but you are free to do it yourself. For your example,

    var o = {_id: Math.random().toString(36).substring(10)};
    collection.insert(o, handleCollision);
    

    works fine, though you have to handle collisions yourself. Then you can use direct string comparisons as needed.

提交回复
热议问题