假设我有3个集Customers
,Contacts
和Messages
Customers {_id, name, address, city, state, zip}
Contacts {_id, customer_id, first_name, last_name, email, phone}
Messages {_id, contact_id, subject, body}
好了,现在我在每个集合上都设置了一些属性和方法,将相关集合作为一个函数引入,可以通过转换直接在文档实例上调用,使我能够以菊花链形式连接到我的像{{#each contact}}{{customer.name}}{{/each}}
这样的模板就是我改变它们的方式。
Contact.prototype = {
constructor: Contact,
customer: function () {
return Customers.findOne({_id: this.customer_id});
},
fullName: function () {
return this.first_name + " " + this.last_name;
},
neverContacted: function () {
if (!Messages.findOne({contact_id: this._id})) {
return true;
} else {
return false;
};
}
};
和
Customer.prototype = {
constructor: Customer,
owner: function () {
user = Meteor.users.findOne({_id: this.user_id});
return user.username || user.emails[0].address;
},
contacts: function () {
contacts = Contacts.find({customer_id: this._id}).fetch();
return contacts;
}
};
我的问题是如何基于客户集合的虚拟属性对客户集合进行查询?
喜欢customers.find().contacts().neverContacted()
答案 0 :(得分:0)
以下是您如何以低效的方式获取所有“联系人”:
var allContacts = [];
customers.find().forEach(function(customer){
var contacts = customer.neverContacted();
contacts.forEach(function(contact){
allContacts.push(contact); //You will want to have an if here to check if it already contains that contact already.
});
});
另一种选择:
setupSearches(customers.find()).contacts()
setupSearches = function(input){
input.contacts = function () {
contacts = input.find({customer_id: this._id}).fetch();
return contacts;
}
return input;
}
答案 1 :(得分:0)
可能没有人回答这个问题,因为涉及很多步骤以及解决问题的不同方法。
我可以告诉你如何开始:你需要用一个允许你在函数中返回“this”关键字的策略来重写你的类。例如,您可以将结果存储到结果属性中,然后测试是否填充结果属性以在其他函数中进行操作。
e.g。
//how you might get the results
customers.find().contacts().neverContacted().result
//in the prototype
contacts: function () {
this.result = Contacts.find({customer_id: this._id}).fetch();
return this;
}
//in the other prototype
neverContacted: function () {
if(this.result){
// do something special and return
}
if (!Messages.findOne({contact_id: this._id})) {
return true;
} else {
return false;
};
}
其次,您可能需要客户从联系人或同一基类继承。
完成后,将结果集存储在属性
中这个问题相当令人困惑,你在扩展收藏吗?
然后你可以使用下划线_.extend()。
更具体的问题,我会尽力给出更好的答案。