在mongoose中id和_id的区别是什么?[英] What is the difference between id and _id in mongoose?

本文是小编为大家收集整理的关于在mongoose中id和_id的区别是什么?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

在猫鼬中,_id和id有什么区别?哪个更好?

推荐答案

来自 documentation :

mongoose默认情况下分配每个模式一个ID虚拟getter 返回文档_id字段施放到字符串或情况下 objectids,其六角形.

因此,基本上,id getter返回文档的_id的字符串表示(默认情况下,该字符串表示为所有mongoDB文档,并且具有默认类型的ObjectId).

.

关于参考更好的内容,这完全取决于上下文(即,您想要ObjectId或a string).例如,如果比较id的s,则字符串可能更好,因为ObjectId的s不会通过平等测试,除非它们是同一实例(无论它们代表什么值).

本文地址:https://www.itbaoku.cn/post/597701.html

问题描述

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

推荐答案

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).