MongoDB:输出“id”而不是“_id”
我正在使用猫鼬(节点),输出 id 而不是 _id 的最佳方式是什么?
I am using mongoose (node), what is the best way to output id instead of _id?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
鉴于您使用的是 Mongoose,您可以使用“虚拟”,它本质上是 Mongoose 创建的假字段。它们不存储在数据库中,只是在运行时填充:
任何时候在您从此架构创建的模型上调用 toJSON 时,它将包含一个与 Mongo 生成的 _id 字段匹配的“id”字段。同样,您可以以相同的方式设置 toObject 的行为。
请参阅:
您可以将其抽象为然后扩展/调用所有模型的 BaseSchema 以将逻辑保留在一处。我在创建 Ember/Node/Mongoose 应用程序时编写了上述内容,因为 Ember 确实更喜欢使用“id”字段。
Given you're using Mongoose, you can use 'virtuals', which are essentially fake fields that Mongoose creates. They're not stored in the DB, they just get populated at run time:
Any time toJSON is called on the Model you create from this Schema, it will include an 'id' field that matches the _id field Mongo generates. Likewise you can set the behaviour for toObject in the same way.
See:
You can abstract this into a BaseSchema all your models then extend/invoke to keep the logic in one place. I wrote the above while creating an Ember/Node/Mongoose app, since Ember really prefers to have an 'id' field to work with.
我用过这个:
我认为如果它们在 virtuals 为 true 时自动抑制 _id ,那就太好了。
I used this :
I think it would be great if they automatically suppress _id when virtuals is true.
从 Mongoose v4.0 开始,此功能的一部分是开箱即用的支持。正如 @Pascal Zajac 所解释的,不再需要手动添加虚拟
id
字段。但是,要导出此字段到JSON ,仍然需要启用虚拟字段的序列化:
As of Mongoose v4.0 part of this functionality is supported out of the box. It's no longer required to manually add a virtual
id
field as explained by @Pascal Zajac.However, to export this field to JSON, it's still required to enable serialization of virtual fields:
我在我的模型上创建了一个 toClient() 方法来执行此操作。这也是重命名/删除您不想发送给客户端的其他属性的好地方:
I create a toClient() method on my models where I do this. It's also a good place to rename/remove other attributes you don't want to send to the client:
这是@user3087827 提供的答案的替代版本。如果您发现 schema.options.toJSON 未定义,那么您可以使用:
Here is an alternative version of the answer provided by @user3087827. If you find that
schema.options.toJSON
is undefined then you can use:有一个“Schema.options.toObject.transform”属性可以执行相反的操作,或者您可以设置为虚拟ID。
there is a "Schema.options.toObject.transform" property to do the reverse or you could just setup as a virtual id.
如果您想使用
id
而不是_id
全局,那么您可以在 mongoose 对象上设置toJSON
配置(从 v5.3 开始):If you want to use
id
instead of_id
globally then you can settoJSON
config on mongoose object(starting from v5.3):还有
normalize-mongoose
一个简单的包,可以删除_id< /code> 和
__v
为您服务。从这样的东西:
假设你有这样的东西:
你将得到这个输出:
There is also
normalize-mongoose
a simple package that removes_id
and__v
for you.From something like this:
So let's say you have something like this:
You will get this output:
用新方法覆盖默认方法
toJSON
:Overwrite default method
toJSON
by new one:为此,我创建了一个易于使用的插件,我将其应用于所有我的项目以及全球所有架构。它将
_id
转换为id
并删除__v
参数。因此它转换为:
更简单、更清晰:
用作全局插件:
或用于特定模式:
希望这对某人有帮助。
I created an easy to use plugin for this purpose that I apply for all my projects and to all schema's globally. It converts
_id
toid
and strips the__v
parameter as well.So it converts:
To a simpler and cleaner:
Usage as a global plugin:
Or for a specific schema:
Hope this helps someone.
您还可以在搜索要返回的项目时使用聚合函数。 $project 将允许您创建字段,您可以执行此操作并将其分配给 _id。
You can also use the aggregate function when searching for items to return. $project will allow you to create fields, which you can do and assign it to _id.
创建基本架构
现在,在您的猫鼬模型中,使用
BaseSchema
而不是Schema
@Pascal Zajac 答案的 Typescript 实现
Create a base schema
Now in your mongoose model, use
BaseSchema
instead ofSchema
Typescript implementation of @Pascal Zajac answer
如果您使用 lodash 来选择您想要的元素,这将适合您。
If you are using lodash to pick the elements you want, this will work for you.
覆盖特定模型架构的 toJSON 方法。
https://mongoosejs.com/docs/api.html#schema_Schema-method
Override
toJSON
method for specific model schema.https://mongoosejs.com/docs/api.html#schema_Schema-method
此配置使用
nestjs + mongoose
:使用以下字段保存到数据库:
对客户端的响应,id 替换为 _id
this config with
nestjs + mongoose
:saved to database with this fields:
response to client , id replaced with _id
还有另一个驱动程序可以执行此操作 http://alexeypetrushin.github.com/mongo-lite 设置 < code>convertId 选项设置为 true。有关更多详细信息,请参阅“默认值和设置”部分。
There's another driver that does that http://alexeypetrushin.github.com/mongo-lite set
convertId
option to true. See "Defaults & Setting" section for more details.默认情况下,Mongoose 为每个模式分配一个 id 虚拟 getter,该 getter 返回文档的 _id 字段转换为字符串,或者在 ObjectIds 的情况下,返回其十六进制字符串。
https://mongoosejs.com/docs/guide.html
Mongoose assigns each of your schemas an id virtual getter by default which returns the document's _id field cast to a string, or in the case of ObjectIds, its hexString.
https://mongoosejs.com/docs/guide.html
方法一:
ret.id = ret._id
delete ret._id
方法二:
Method 1:
ret.id = ret._id
delete ret._id
Method 2:
您还可以使用 pre 'save' 挂钩:
You can also use pre 'save' hook: