我的Firebase数据以这种方式组织:
+ myappname
+ customers
+ -JV2NQv3GmoM81zdUfTe
+ name: "Mary"
+ age: "24"
+ ...
+ -JV2N9NnItCfz5vB04RS
+ name: "John"
+ age: "32"
+ ...
+ ...
+ ...
如何通过名称检索客户?
该名称保证是独一无二的
这是我的客户服务,目前:
app.factory('Customer', function ($firebase, FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL + 'customers');
var customers = $firebase(ref);
var Customer = {
all: customers,
create: function (customer) {
return customers.$add(customer).then(function (ref) {
var customerId = ref.name();
return customerId;
});
},
set: function(customerId, customer) {
return customers.$child(customerId).$set(customer);
},
find: function (customerId) {
return customers.$child(customerId);
},
findByName: function (customerName) { // TODO...
},
delete: function (customerId) {
var customer = Customer.find(customerId);
customer.deleted = true;
customer.$on('loaded', function () {
customers.$child(customerId).$set(customer);
});
}
};
return Customer;
});
我应该在每个findByName()调用上扫描所有客户吗? 或者我应该建立类似“二级指数”的东西? 请一些建议,我刚开始......: - (
答案 0 :(得分:2)
感谢Kato指示和Frank van Puffelen的建议,我终于解决了自己的问题
我确实在我的Firebase中添加了一个“index”,“customersByName”(记住“磁盘空间便宜,用户的时间不是”Firebase座右铭...... :-)。
我没有按照提到的答案中的指示,因为我认为这个解决方案更常用:它可以扩展多个“索引”......
我想在这里发布,希望它对其他人有用。
我想看看评论:这个解决方案有可能存在缺陷吗?对于某些用例,总体而言,这是一个明智的解决方案吗?
app.factory('Customer', function ($firebase, FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL + 'customers');
var customers = $firebase(ref);
var refByName = new Firebase(FIREBASE_URL + 'customersByName');
var customersByName = $firebase(refByName);
var Customer = {
all: customers,
create: function (customer) {
return customers.$add(customer).then(function (ref) {
var customerId = ref.name();
customersByName.$child(customer.name).$set(customerId);
return customerId;
});
},
set: function(customerId, customer) {
var oldname = customers.$child(customerId).name;
if (customer.name !== oldname) {
customersByName.$remove(oldname);
}
customersByName.$child(customer.name).$set(customerId);
return customers.$child(customerId).$set(customer);
},
find: function (customerId) {
return customers.$child(customerId);
},
findByName: function (customerName) {
return customersByName.$child(customerName);
},
delete: function (customerId) {
var customer = Customer.find(customerId);
customer.deleted = true;
customer.$on('loaded', function () {
customersByName.$remove(customer.name);
customers.$child(customerId).$set(customer);
});
}
};
return Customer;
});