Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a variable as a field name in a Mongo query in Meteor?

How would I go about using a variable as a field name in a Mongo query in a Meteor application.

Here is an example...

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()

where

Session.get('child_collection_name').decapitalise()

returns users

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.

like image 413
Steeve Cannon Avatar asked Aug 19 '12 03:08

Steeve Cannon


People also ask

How to use variables in MongoDB?

To use variables, work with var in MongoDB. Let us create a collection with documents − Display all documents from a collection with the help of find () method −

How to make a MongoDB query not literal?

Simply enclosing [query] in brackets tells mongodb that it's not literal, but rather a path. Show activity on this post. use like this if the object is nested.

How do I use a field name in MATLAB?

Field names, like variable names, must begin with a letter, can contain letters, digits, or underscore characters, and are case sensitive. To avoid potential conflicts, do not use the names of existing variables or functions as field names. Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Can I use a variable name as a field name?

Field names, like variable names, must begin with a letter, can contain letters, digits, or underscore characters, and are case sensitive. To avoid potential conflicts, do not use the names of existing variables or functions as field names.


1 Answers

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();

Does that do the trick?

like image 120
Geoff Avatar answered Oct 10 '22 21:10

Geoff