Ember-data:store.query正确返回数组但仍然抛出错误'期待数组,找到单个记录'

时间:2016-04-28 19:36:13

标签: ember.js ember-data

我有以下“获取所有地点”的快捷路线:

router.get('/', function(req, res){

    let q = req.query;

    let locations = Location.find({organization: q.organization});

    locations.then(r => res.status(200).send(r))
        .catch(err => res.status(500).send(err));
});

这个ember模型钩子正确触发它:

model(){
    return this.store.findRecord("user", this.get('session.currentUser.id'))
      .then(user => user.get('organization'))
      .then(org => this.store.query("location", {organization: org.id}))
}

现在,此查询正在使用params:

向以下网址发送get请求
GET /locations?organization=571974742ce868d575b79d6a

我的服务器返回了200个成功代码,但模型钩子因此错误而崩溃:

query to locations failed with error: Error: Assertion Failed: The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use `store.queryRecord` to query for a single record.

为同一地址创建邮递员请求:

localhost:3200/locations?organization=571974742ce868d575b79d6a

我看到一个返回的数组,填充了正确的对象,如下所示:

[{object1}, {object2]

这似乎是正确的回应。为什么Ember会告诉我它只收到一条记录?

当调用模型钩子时,它甚至会抛出这个警告:

WARNING: Encountered "0" in payload, but no model was found for model name "0" (resolved model name using lc-dash@serializer:application:.modelNameFromPayloadKey("0"))

修改

实现这可能是序列化程序/适配器错误:

// app/adapters/application.js

import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

export default DS.RESTAdapter.extend(DataAdapterMixin, {
    host: 'http://localhost:3200',
    authorizer: 'authorizer:application'
});

我的序列化工具中可能缺少某些东西?

// app/serializers/application.js

import DS from 'ember-data';

export default DS.RESTSerializer.extend({});

2 个答案:

答案 0 :(得分:3)

The RESTSerializer expects arrays of objects to be delivered inside a payload key matching the model name pluralized:

{
  "organizations": [
    {
      "id": 1,
      "key1": "value1",
      "key2": "value2"
    },
    {
      "id": 2,
      "key1": "value3",
      "key2": "value4"
    }
  ]
}

Alternatively, you can use the JsonSerializer if you would prefer not to send a payload key.

答案 1 :(得分:1)

仅供参考,请参阅下表,了解服务器是否应以单数或复数形式返回响应。

| Async from server/store | Sync from store | Query server Single Record | findRecord(type,id) | peekRecord(type, id) | queryRecord(type, {query}) All Records | findAll(type) | peekAll(type) | query(type, {query})

参考:

1。CRUD with Ember (+ Data)

2。Ember_data_rest_api.md