node.js 猫鼬中的 id 和 _id 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15724272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between id and _id in mongoose?
提问by Ari Porad
What is the difference between _idand idin mongoose? Which is better for referencing?
猫鼬_id和id猫鼬有什么区别?哪个更适合参考?
回答by jmar777
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.
默认情况下,Mongoose 为您的每个模式分配一个 id 虚拟 getter,它将文档 _id 字段转换为字符串,或者在 ObjectIds 的情况下,返回其 hexString。
So, basically, the idgetter 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).
因此,基本上,idgetter 返回文档的字符串表示_id(默认情况下将其添加到所有 MongoDB 文档中,并且默认类型为ObjectId)。
Regarding what's better for referencing, that depends entirely on the context (i.e., do you want an ObjectIdor 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).
关于什么更适合引用,这完全取决于上下文(即,您想要 anObjectId还是 a string)。例如,如果比较id's,则字符串可能更好,因为ObjectId's 不会通过相等测试,除非它们是相同的实例(无论它们代表什么值)。

