diff --git a/examples/index.html b/examples/index.html
index fb69de55..ff6592b0 100644
--- a/examples/index.html
+++ b/examples/index.html
@@ -565,7 +565,7 @@
Output
$('.set-mongo').on('click', function() {
$('#builder').queryBuilder('setRulesFromMongo', {
"$or": [{
- "name": {
+ "username": {
"$regex": "^(?!Mistic)"
}
}, {
diff --git a/src/plugins/mongodb-support/plugin.js b/src/plugins/mongodb-support/plugin.js
index eca501bc..93a17348 100644
--- a/src/plugins/mongodb-support/plugin.js
+++ b/src/plugins/mongodb-support/plugin.js
@@ -270,15 +270,7 @@ QueryBuilder.extend(/** @lends module:plugins.MongoDbSupport.prototype */ {
var opVal = mdbrl.call(self, value);
- /**
- * Returns a filter identifier from the MongoDB field
- * @event changer:getMongoDBFieldID
- * @memberof module:plugins.MongoDbSupport
- * @param {string} field
- * @param {*} value
- * @returns {string}
- */
- var id = self.change('getMongoDBFieldID', field, value);
+ var id = self.getMongoDBFieldID(field, value);
/**
* Modifies the rule generated from the MongoDB expression
@@ -320,6 +312,39 @@ QueryBuilder.extend(/** @lends module:plugins.MongoDbSupport.prototype */ {
*/
setRulesFromMongo: function(query) {
this.setRules(this.getRulesFromMongo(query));
+ },
+
+ /**
+ * Returns a filter identifier from the MongoDB field.
+ * Automatically use the only one filter with a matching field, fires a changer otherwise.
+ * @param {string} field
+ * @param {*} value
+ * @fires module:plugins.MongoDbSupport:changer:getMongoDBFieldID
+ * @returns {string}
+ * @private
+ */
+ getMongoDBFieldID: function(field, value) {
+ var matchingFilters = this.filters.filter(function(filter) {
+ return filter.field === field;
+ });
+
+ var id;
+ if (matchingFilters.length === 1) {
+ id = matchingFilters[0].id;
+ }
+ else {
+ /**
+ * Returns a filter identifier from the MongoDB field
+ * @event changer:getMongoDBFieldID
+ * @memberof module:plugins.MongoDbSupport
+ * @param {string} field
+ * @param {*} value
+ * @returns {string}
+ */
+ id = this.change('getMongoDBFieldID', field, value);
+ }
+
+ return id;
}
});
diff --git a/tests/plugins.mongo-support.module.js b/tests/plugins.mongo-support.module.js
index 68e4a329..73ff20f9 100644
--- a/tests/plugins.mongo-support.module.js
+++ b/tests/plugins.mongo-support.module.js
@@ -62,6 +62,48 @@ $(function(){
);
});
+ QUnit.test('Automatically use filter from field', function(assert) {
+ var rules = {
+ condition: 'AND',
+ rules: [
+ {
+ id: 'name',
+ operator: 'equal',
+ value: 'Mistic'
+ }
+ ]
+ };
+
+ var mongo = {
+ $and: [{
+ username: 'Mistic'
+ }]
+ };
+
+ $b.queryBuilder({
+ filters: [
+ {
+ id: 'name',
+ field: 'username',
+ type: 'string'
+ },
+ {
+ id: 'last_days',
+ field: 'display_date',
+ type: 'integer'
+ }
+ ]
+ });
+
+ $b.queryBuilder('setRulesFromMongo', mongo);
+
+ assert.rulesMatch(
+ $b.queryBuilder('getRules'),
+ rules,
+ 'Should use "name" filter from "username" field'
+ );
+ });
+
var all_operators_rules = {
condition: 'AND',