3

我正在使用 ember.js 和沙发数据库后端开发应用程序。到目前为止,我使用 ember-resource 作为数据库驱动程序,但我正在考虑切换到 ember-data,因为这似乎更可持续。

由于我正在使用 couch DB,因此我正在使用Couch DB-Adapter

我的数据库中的文档包含完整的对象结构,因此我必须在数据库驱动程序中指定嵌入的对象。

但是,尽管我将我的子对象指定为嵌入的,但 ember-data 似乎使用单独的请求来获取这些对象,而不是仅仅将它们从主 json 中取出。

我的对象定义如下:

App.UserProfile = DS.Model.extend({
    type:              DS.attr('string'),
    fullname:          DS.attr('string'),
    email:             DS.attr('string'),
    pictureUrl:        DS.attr('string'),
    social:            DS.hasMany('App.SocialWebAccount', { embedded: true }),
    .....
});

App.SocialWebAccount = DS.Model.extend({
    profile: DS.belongsTo('CaiMan.UserProfile'),
    site:    DS.attr('string'),
    account: DS.attr('string'),
    .....
});

并且服务器数据是这样的:

{
  "_id": "thoherr",
  "_rev": "55-d4abcb745b42fe61f1a2f3b31c461cce",
  "type": "UserProfile",
  "fullname": "Thomas Herrmann",
  "email": "test@thoherr.de",
  "pictureUrl": "",
  "social": [
      {
          "site": "socialFacebook",
          "account": "thoherr"
      },
      {
          "site": "socialXing",
          "account": "Thomas_Herrmann7"
      },
      {
          "site": "socialEmail",
          "account": "test@thoherr.de"
      }
   ]
}

加载后,UserProfile 确实包含我的社交数据的 ArrayProxy,它由三个条目填充,但它们都是未定义的,而不是 SocialWebAccount 的实例!

如果我尝试访问这个数组,ember-data 似乎会执行单独的数据库访问来获取数据,这会导致错误,因为沙发 DB-adapter 访问了一个 _id 字段,该字段在 undefined 中不可用。...

我错过了什么?

我认为“嵌入式”标志表明数据已经在 json 中并且可以从 json 实例化对象?

为什么 ember-data 会尝试获取嵌入的数据?

有什么提示吗?

4

1 回答 1

3

嵌入式选项似乎最近发生了变化。我在ember-data github 上的测试文件中找到了一些信息。

在这些测试文件中,嵌入的内容是这样定义的

Comment = App.Comment = DS.Model.extend({
  title: attr('string'),
  user: DS.belongsTo(User)
});

Post = App.Post = DS.Model.extend({
  title: attr('string'),
  comments: DS.hasMany(Comment)
});
Adapter = DS.RESTAdapter.extend();
Adapter.map(Comment, {
  user: { embedded: 'always' }
});

或者

Adapter = DS.RESTAdapter.extend();
Adapter.map(Comment, {
  user: { embedded: 'load' }
});

'always' 似乎用于没有 id 的嵌入式数据(您的情况),例如

id: 1,
title: "Why not use a more lightweight solution?",
user: {
  name: "mongodb_expert"
}

'load' 似乎用于带有 id 的嵌入式数据

id: 1,
user: {
  id: 2,
  name: "Yehuda Katz"
}

希望它对您的特定情况有所帮助。最近我在 hasMany 关系方面遇到了很多麻烦(我不得不修改我的适配器才能让它工作)

于 2013-01-07T23:38:07.093 回答