问题
I'm trying to use something as follows
collection.find({"myField."+variable : {$exists: true})
But obviously that doesn't work because the collections doesn't take strings. Instead, I tried building a a fully query string in JSON but that won't parse correctly because I'm just searching for a field name and not an entire object
var qry = '{"myField.'+variable+'"}'; //no go
I've also tried the meteor collection fields logic
var qry = 'myField.'+variable;
collection.find({}, {fields: {qry: 1}})
to no avail. I know that a query can take a JSON object but I'm not sure how to write this up.
回答1:
This can be accomplished using bracket notation
var fieldQuery = {};
fieldQuery["myField"+variable] = {$exists: true};
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation
回答2:
Give this a try:
var selector = {};
selector["myField." + variable] = {$exists: true};
Collection.find(selector);
来源:https://stackoverflow.com/questions/31442128/mongodb-meteor-collection-check-if-subdocument-field-exists-when-field-is-a-vari