What is the difference between id and _id in mongoose?

前端 未结 1 352
走了就别回头了
走了就别回头了 2020-12-07 18:46

What is the difference between _id and id in mongoose? Which is better for referencing?

相关标签:
1条回答
  • 2020-12-07 19:11

    From the documentation:

    Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _id field cast to a string, or in the case of ObjectIds, its hexString.

    So, basically, the id getter returns a string representation of the document's _id (which is added to all MongoDB documents by default and have a default type of ObjectId).

    Regarding what's better for referencing, that depends entirely on the context (i.e., do you want an ObjectId or a string). For example, if comparing id's, the string is probably better, as ObjectId's won't pass an equality test unless they are the same instance (regardless of what value they represent).

    0 讨论(0)
提交回复
热议问题