Jaybruh
Jaybruh

Reputation: 343

How to only run a function if a specific field in a Mongo collection contains a specific value?

I stored a "key" (and some other unimportant information) as an array field in a collection called "storedKeys".

This looks like:

{
    "_id" : "Company(02fd8fba13cf51cf)",
    "infos" : {
        "companyName" : "company",
        "street" : "exampleStreet",
        "number" : "123",
        "city" : exampleCity",
        "createdAt" : ISODate("2017-06-24T13:20:09.771Z")
    },
    "key" : ["123456789"]
}

Now, I want to use this "key" field as a permission to run some updates in other collections by calling a Meteor method. Additionally, this method should only be executed in case that the right _id in storedKeys exists.

More precisely: Execute the method if the vars which are put into the method call by the eventhandler match the defined fields in the collection storedKeys. Otherwise, throw an error and do not execute the method.

For that purpose, I tried to call a method by a submit form and than tried to use an if-clause with a find({}) function in the server side method like so:

Client (trigger method)

Template.keyCollectionThing.events({
"submit form": function (e) {
e.preventDefault();
var key = "123456789";
var id = "Company(02fd8fba13cf51cf)";
Meteor.call('updateOtherCollections', key, id);
}
});

Server (run method)

    Meteor.methods({
      'updateOtherCollections': function(key, id) {

    if(storedKeys.find({"key": key}) && storedKeys.find({"_id": id})) {

       Meteor.users.update(
            {'_id': this.userId
          }, {
              $push: {
                'pushedId': id
                    }
              });

      otherDB.update(
      {'_id': this.userId
      }, {
        $push: {
          'pushedId': id
        }
      }
      );

      storedKeys.update(
      {'_id': id
    }, {
      $set: {
        "key": []
      }
    });
  }} 
 });

However, the problem is, that the method is always running correctly, even if there is no key in storedKeys or the _id in storedKeys doesn´t exist. So, there is no verification which I expected by the if () and find({}) thing. The method is always executed and the collections are updated (you can open the door without even having a key).

Upvotes: 0

Views: 40

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20226

.find() returns a cursor which is a function which will always be truthy.

If you're expecting a single document to be found then use .findOne(). If you're expecting > 0 to be found then you can test .find(query).count() (0 will be falsy, any other number will be truthy)

Upvotes: 2

Related Questions