javascriptfunctionmeteorsimple-schemameteor-collection2

Javascript function is executed before it is called


I have a javascript function complaining that a call within its body is not a function before it is called. Could someone please help me explain this?

Context: I am using Meteor and Collection2 and I would like to use a function for reuse at different attributes of my Schemas. Precisely, I would like to do the following:

function foo (autoVal, self){
  if(something){
     return autoVal;
  }else{
     return self.unset();
  }
}

export const myCollection = new Mongo.Collection('myCollection');

const Schema = new SimpleSchema({
   my_field:{
      type:Boolean,
      autoValue: foo(false,this),
   }
});

myCollection.attachSchema(Schema);

When I save this and run Meteor, it does not launch and I get the following error message:

TypeError: self.unset is not a function

I feel that I am missing something about how javascript functions are called or executed, can someone point out why is this happening?


Solution

  • Try this:

    function foo (autoVal, self){
      if(something){
         return autoVal;
      }else{
         return self.unset();
      }
    }
    
    export const myCollection = new Mongo.Collection('myCollection');
    
    const Schema = new SimpleSchema({
       my_field:{
          type:Boolean,
          autoValue() {
            return foo(false, this);
          }
       }
    });
    
    myCollection.attachSchema(Schema);