MongoDB:输出'id'而不是'_id'
我正在使用mongoose(节点),什么是最好的方式来输出id而不是_id?
我在我的模型上创build一个toClient()方法,我这样做。 这也是一个很好的地方,可以重新命名/删除不想发送给客户端的其他属性:
Schema.method('toClient', function() { var obj = this.toObject(); //Rename fields obj.id = obj._id; delete obj._id; return obj; });
鉴于您使用的是Mongoose,您可以使用“虚拟”,这实质上是Mongoose创build的虚假字段。 他们没有存储在数据库中,他们只是在运行时填充:
// Duplicate the ID field. Schema.virtual('id').get(function(){ return this._id.toHexString(); }); // Ensure virtual fields are serialised. Schema.set('toJSON', { virtuals: true });
任何时候在你从这个Schema创build的模型上调用JSON时,都会包含一个与id生成的_id字段相匹配的“id”字段。 同样,你可以用同样的方法设置toObject的行为。
看到:
- http://mongoosejs.com/docs/api.html
- http://mongoosejs.com/docs/guide.html#toJSON
- http://mongoosejs.com/docs/guide.html#toObject
你可以将这个抽象成BaseSchema,然后扩展/调用,把逻辑保存在一个地方。 我在创build一个Ember / Node / Mongoose应用程序的时候写了上面的内容,因为Ember真的更喜欢使用一个“id”字段。
//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; }
有一个“Schema.options.toObject.transform”属性来做相反的事情,或者你可以设置为一个虚拟的ID。
这是由@ user3087827提供的答案的替代版本。 如果你发现schema.options.toJSON
是未定义的,那么你可以使用:
schema.set('toJSON', { transform: function (doc, ret, options) { ret.id = ret._id; delete ret._id; delete ret.__v; } });
作为Mongoose v4.0的一部分,这个function是开箱即用的 。 不再需要手动添加@Pascal Zajac解释的虚拟id
字段。
Mongoose默认为每个模式分配一个id虚拟getter,它将文档_id字段转换为string,或者ObjectIds的hexString。 如果你不想在模式中添加一个id getter,你可以禁止它在模式构造时传递这个选项。 资源
但是,要将此字段导出为JSON ,仍然需要启用虚拟字段的序列化:
Schema.set('toJSON', { virtuals: true });
我用这个:
schema.set('toJSON', { virtuals: true, versionKey:false, transform: function (doc, ret) { delete ret._id } });
我认为如果他们在virtuals为true时自动抑制_id会很好。
我为此创build了一个易于使用的插件 ,我申请了我的所有项目以及全局的所有模式。 它将_id
转换为id
并__v
参数。
所以它转换:
{ "_id": "400e8324a71d4410b9dc3980b5f8cdea", "__v": 2, "name": "Item A" }
更简单,更清洁:
{ "id": "400e8324a71d4410b9dc3980b5f8cdea", "name": "Item A" }
用作全局插件:
const mongoose = require('mongoose'); mongoose.plugin(require('meanie-mongoose-to-json'));
或者对于特定的模式:
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const MySchema = new Schema({}); MySchema.plugin(require('meanie-mongoose-to-json'));
希望这有助于某人。
还有另一个驱动程序, http: convertId
将convertId
选项设置为true。 有关更多详细信息,请参阅“默认设置”部分。
search要返回的项目时,也可以使用聚合函数。 $项目将允许您创build字段,您可以执行并将其分配给_id。
<model>.aggregate([{$project: {_id: 0, id: '$_id'}], (err, res) => { // })