MongoDb返回表单_id
的id。我想确保前端(ember.js应用程序)总是接收id
代替。我可以在客户端上写一个序列化器,但我认为可能有一个更简单的解决方案,可以在数据库级别或在express服务器应用程序中实现。
我尝试使用虚拟属性,但这似乎不起作用。
ActionSchema = mongoose.Schema(
title: type: mongoose.Schema.Types.Mixed
reduction: type: Number
description: type: mongoose.Schema.Types.Mixed
category: type: String
)
ActionSchema.virtual('id').get(->
@_id
)
我使用自定义toJSON
方法解决了这个问题。在模式声明后的模型中:
schema.options.toJSON =
transform: (doc, ret, options) ->
ret.id = ret._id
delete ret._id
delete ret.__v
ret
然后在我的控制器中,当我想返回格式正确的JSON响应时,我使用了item.toJSON()
。
我用这篇博文找到了我的答案:http://ryanchristiani.com/working-with-ember-data-node-express-and-mongodb/
简单的方法是在Ember中编写rest序列化器,如下所示:export default DS.RESTSerializer.extend({
primaryKey: '_id',
serializeId: function(id) {
return id.toString();
}
});