如何在Meteor的Mongo查询中使用变量作为字段名称? [英] How do I use a variable as a field name in a Mongo query in Meteor?
问题描述
如何在Meteor应用程序的Mongo查询中使用变量作为字段名称。
How would I go about using a variable as a field name in a Mongo query in a Meteor application.
这是一个示例...
在大写子集的父ID的集合名称后,在我的请求控制器集合上运行查找。孩子是用户字段。
This runs a find on my request controllers collection after capitalizing the collection name for the parent id of a child. The child is the users field.
window[Meteor.request.controller.capitalise()]["find"]({ _id: Session.get('parent_id'), users: params.child }).count()
正如您所看到的,我的控制器是集合项的变量名,这使我可以使用一行代码来查找控制器/集合的子代,但我需要能够设置子字段命名为变量。在上面的示例中,用户但我希望它是变量名。
As you can see my controller is a variable name for the collection item which allows me to have a single line of code for finding children of controller/collections but I need to be able to set the child field name to a variable. In the above example that would be users but I want it to be a variable name.
我试过这个但是没有用。
I have tried this but it does not work.
window[Meteor.request.controller.capitalise()]["find"]({ _id: Session.get('parent_id'), [Session.get('child_collection_name').decapitalise()]: params.child }).count()
其中
Session.get('child_collection_name').decapitalise()
返回用户
任何想法?如果我可以弄清楚如何在meteor中使用mongo查询中的变量名,那么它将显着减少我的代码占用空间。
Any ideas? If I can figure out how to use a variable name in a mongo query in meteor it would reduce my code footprint significantly.
推荐答案
查询只是一个JavaScript对象,因此您可以逐步构建它:
The query is just a JavaScript object, so you can build it step by step:
var query = { _id: Session.get('parent_id') };
var myCustomField = Session.get('child_collection_name').decapitalise();
var myCustomValue = params.child;
query[myCustomField] = myCustomValue;
var count = SomeCollection.find(query).count();
这样做可以吗?
这篇关于如何在Meteor的Mongo查询中使用变量作为字段名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!