简而言之,我正在获取一个集合,但之后我无法使用它id
或cid
.
对于这个问题,请考虑我的两个 REST 端点/sites
,/sites/some-site-id/entities
两者都是集合。这是我的模型/收藏:sites
entities
模型/系列
var ROOT = 'http://localhost:5000';
Entity = Backbone.Model.extend({
idAttribute: "_id",
defaults: {
xpos: 10,
ypos: 10,
site: "default"
}
});
Entities = Backbone.Collection.extend({
model: Entity,
ownUrl: '/entities',
site: {},
url: function() {
return ROOT + "/sites/" + (this.site? this.site : 'null') + this.ownUrl;
},
initialize: function(models, options) {
if(!options.site) throw new Error("No site associated with entities");
if(!options.site.get("_id")) throw new Error("Associated site has no _id");
this.site = options.site.get("_id");
}
});
Site = Backbone.Model.extend({
idAttribute: "_id",
defaults: {
name: "default",
description: "My site"
}
});
Sites = Backbone.Collection.extend({
model: Site,
url: ROOT + "/sites"
});
我的问题是,当我为网站获取实体时,我无法使用集合上的get
方法从集合中查找某个实体。我只是得到undefined
回报。
这就是我测试它的方式(entities.fetch 将获得 4 个实体):
测试代码
var site1 = new Site({id : "52813a2888c84c9953000001"});
sites.add(site1);
site1.fetch({success: function(model, response, options) {
entities = new Entities([], {site: site1});
entities.fetch({success: function(model, response, options) {
entities.each(function (entity) {
console.log("entity.get(\"_id\") = " + entity.get("_id"));
console.log("entity.id = " + entity.id);
console.log("Looking up entity using id (" + entity.get("_id") + "): " + entities.get(entity.get("_id")));
console.log("Looking up entity using cid (" + entity.cid + "): " + entities.get(entity.cid));
console.log("");
});
}});
}});
当我运行它时,我得到:
测试结果
entity.id = undefined
entity.get("_id") = 528146ade34176b255000003
Looking up entity using id (528146ade34176b255000003): undefined
Looking up entity using cid (c1): undefined
entity.id = undefined
entity.get("_id") = 528146ade34176b255000002
Looking up entity using id (528146ade34176b255000002): undefined
Looking up entity using cid (c2): undefined
entity.id = undefined
entity.get("_id") = 528146ade34176b255000001
Looking up entity using id (528146ade34176b255000001): undefined
Looking up entity using cid (c3): undefined
entity.id = undefined
entity.get("_id") = 528146ade34176b255000004
Looking up entity using id (528146ade34176b255000004): undefined
Looking up entity using cid (c4): undefined
我期望集合返回特定实体。它与我的特殊idAttribute“_id”(为了符合mongodb)有关吗?
编辑
显然它似乎与我的 idAttribute 有关。因为如果我为每个返回的实体添加一个“id”字段,我可以使用它的 id 来查找实体。就像在服务器端一样:
function getEntitiesInSite(siteId, fun) {
db.siteentities.find({site: mongojs.ObjectId(siteId)}, function(err, entities) {
entities.forEach(function (entity) {
entity.id = entity._id;
});
fun(err, entities);
});
}
这不完全是我想要的,我可以想象我将来会遇到其他问题,因为不一致的 id(同时具有id
和_id
字段)。