猫鼬中的 id 和 _id 有什么区别? [英] What is the difference between id and _id in mongoose?
问题描述
mongoose 中的 _id
和 id
有什么区别?哪个更适合参考?
What is the difference between _id
and id
in mongoose? Which is better for referencing?
推荐答案
来自 文档:
默认情况下,Mongoose 为您的每个架构分配一个 id 虚拟 getter它返回文档 _id 字段转换为字符串,或者在这种情况下ObjectIds,它的十六进制字符串.
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.
所以,基本上,id
getter 返回文档 _id
的字符串表示(默认情况下,它被添加到所有 MongoDB 文档中,并且默认类型为 ObjectId
).
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
).
关于什么更适合引用,这完全取决于上下文(即,您想要 ObjectId
还是 string
).例如,如果比较 id
的字符串可能更好,因为 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).
这篇关于猫鼬中的 id 和 _id 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!