id和_id在mongoose有什么区别? [英] 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及其hexString的情况下。
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
默认情况下是文档,并且默认类型为 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
或字符串
)。例如,如果比较 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在mongoose有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!