node.js MongoDB:输出“id”而不是“_id”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7034848/
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
MongoDB: output 'id' instead of '_id'
提问by Johnny
I am using mongoose (node), what is the best way to output id instead of _id?
我正在使用猫鼬(节点),输出 id 而不是 _id 的最佳方式是什么?
采纳答案by evilcelery
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:
我在执行此操作的模型上创建了一个 toClient() 方法。这也是重命名/删除您不想发送给客户端的其他属性的好地方:
Schema.method('toClient', function() {
var obj = this.toObject();
//Rename fields
obj.id = obj._id;
delete obj._id;
return obj;
});
回答by Pascal Zajac
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:
鉴于您使用的是 Mongoose,您可以使用“虚拟”,它们本质上是 Mongoose 创建的假字段。它们不存储在数据库中,它们只是在运行时填充:
// Duplicate the ID field.
Schema.virtual('id').get(function(){
return this._id.toHexString();
});
// Ensure virtual fields are serialised.
Schema.set('toJSON', {
virtuals: true
});
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.
任何时候在您从此架构创建的模型上调用 toJSON 时,它都会包含一个与 Mongo 生成的 _id 字段相匹配的“id”字段。同样,您可以以相同的方式设置 toObject 的行为。
See:
看:
- http://mongoosejs.com/docs/api.html
- http://mongoosejs.com/docs/guide.html#toJSON
- http://mongoosejs.com/docs/guide.html#toObject
- http://mongoosejs.com/docs/api.html
- http://mongoosejs.com/docs/guide.html#toJSON
- http://mongoosejs.com/docs/guide.html#toObject
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.
您可以将其抽象为所有模型的 BaseSchema,然后扩展/调用以将逻辑保持在一个位置。我在创建 Ember/Node/Mongoose 应用程序时写了上面的内容,因为 Ember 真的更喜欢有一个“id”字段来使用。
回答by xaviert
As of Mongoose v4.0part of this functionality is supported out of the box. It's no longer required to manually add a virtual idfield as explained by @Pascal Zajac.
从 Mongoose v4.0 开始,此功能的一部分是开箱即用的。id如@Pascal Zajac 所述,不再需要手动添加虚拟字段。
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. If you don't want an id getter added to your schema, you may disable it passing this option at schema construction time. Source
默认情况下,Mongoose 为您的每个模式分配一个 id 虚拟 getter,它将文档 _id 字段转换为字符串,或者在 ObjectIds 的情况下,返回其 hexString。如果您不希望将 id getter 添加到您的架构中,您可以在架构构建时禁用它传递此选项。来源
However, to exportthis field to JSON, it's still required to enableserialization of virtual fields:
但是,要将此字段导出为JSON,仍然需要启用虚拟字段的序列化:
Schema.set('toJSON', {
virtuals: true
});
回答by Tom Makin
Here is an alternative version of the answer provided by @user3087827. If you find that schema.options.toJSONis undefined then you can use:
这是@user3087827 提供的答案的替代版本。如果您发现schema.options.toJSON未定义,则可以使用:
schema.set('toJSON', {
transform: function (doc, ret, options) {
ret.id = ret._id;
delete ret._id;
delete ret.__v;
}
});
回答by user3087827
//Transform
Schema.options.toJSON.transform = function (doc, ret, options) {
// remove the _id of every document before returning the result
ret.id = ret._id;
delete ret._id;
delete ret.__v;
}
there is a "Schema.options.toObject.transform" property to do the reverse or you could just setup as a virtual id.
有一个“Schema.options.toObject.transform”属性可以做相反的事情,或者您可以设置为虚拟ID。
回答by Benamar
I used this :
我用过这个:
schema.set('toJSON', {
virtuals: true,
versionKey:false,
transform: function (doc, ret) { delete ret._id }
});
I think it would be great if they automatically suppress _id when virtuals is true.
我认为如果他们在 virtuals 为真时自动抑制 _id 会很棒。
回答by Adam Reis
I created an easy to use pluginfor this purpose that I apply for all my projects and to all schema's globally. It converts _idto idand strips the __vparameter as well.
为此,我创建了一个易于使用的插件,我将其应用于我的所有项目和全局所有架构。它也转换_id为id并去除__v参数。
So it converts:
所以它转换:
{
"_id": "400e8324a71d4410b9dc3980b5f8cdea",
"__v": 2,
"name": "Item A"
}
To a simpler and cleaner:
更简单更干净:
{
"id": "400e8324a71d4410b9dc3980b5f8cdea",
"name": "Item A"
}
Usage as a global plugin:
用作全局插件:
const mongoose = require('mongoose');
mongoose.plugin(require('meanie-mongoose-to-json'));
Or for a specific schema:
或者对于特定的架构:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MySchema = new Schema({});
MySchema.plugin(require('meanie-mongoose-to-json'));
Hope this helps someone.
希望这可以帮助某人。
回答by Stan Fad
Overwrite default method toJSONby new one:
toJSON用新方法覆盖默认方法:
schema.method('toJSON', function () {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
回答by Abraham Hernandez
There is also normalize-mongoosea simple package that removes _idand __vfor you.
还有normalize-mongoose一个简单的包可以为您删除_id和__v。
From something like this:
从这样的事情:
import mongoose from 'mongoose';
import normalize from 'normalize-mongoose';
const personSchema = mongoose.Schema({ name: String });
personSchema.plugin(normalize);
const Person = mongoose.model('Person', personSchema);
const someone = new Person({ name: 'Abraham' });
const result = someone.toJSON();
console.log(result);
So let's say you have something like this:
所以假设你有这样的事情:
{
"_id": "5dff03d3218b91425b9d6fab",
"name": "Abraham",
"__v": 0
}
You will get this output:
你会得到这个输出:
{
"id": "5dff03d3218b91425b9d6fab",
"name": "Abraham"
}
回答by Ivor Scott
If you are using lodash to pick the elements you want, this will work for you.
如果你使用 lodash 来选择你想要的元素,这对你有用。
UserSchema.virtual('id').get(function(){
return this._id.toHexString();
});
UserSchema.set('toObject', { virtuals: true })
UserSchema.methods.toJSON = function() {
return _.pick(
this.toObject(),
['id','email','firstName','lastName','username']
);

