Meteor Methods

Learn about the syntax of Meteor Methods and how to call them.

Defining Meteor Methods

Meteor Methods are defined by the Meteor guide as RPC systems similar to REST APIs or HTTPs. A Meteor Method is like a POST request to a server. Meteor Methods run on both the client and server.

Syntax in Method

Meteor.methods({
   "links.insertNewLink": function (){
    //this function runs when the method 
    //is called on the 
    //client
  }
});

Meteor Methods contain a function that takes an object. Each key of the object represents a function that can be called by the client. It’s usually good practice to name methods starting with the collection name followed by the method’s job.

The code example above contains a method name called links.insertNewLink . Notice that this method inserts new data into a collection called links.

Open the imports/api/methods.js file in the application below. This file is where Meteor Methods are defined. A method is defined on line 5 with the name links.insertNewLink. The naming convention for defining methods was followed. As we can see, this method inserts a new link in the links collection.

In line 3, we import the check package that comes with Meteor. The check package, as its name suggests, is used to validate the variable coming into the methods to ensure that it’s of the right type. We check if the link is a type of object.

Calling Meteor Methods

The client can call the Meteor Methods by using the method name and passing the parameters that are used by the method, if any. The last parameter passed to a Meteor Method is a callback function that takes an error object as the first parameter along with the data returned from the methods.

Open the imports/ui/Hello.jsx file. We have two input textboxes that are used to collect the title and URL of a link. With a click of a button, the saveNewLinks method is called. Inside the saveNewLinks method on line 24, a call is made to the insert.insertNewLink method. The insert.insertNewLink method receives a link object that contains a title and url key as an input.

The method runs on the server and returns the id of the newly inserted link. When the method finishes executing, it calls the callback function with an error object as the first parameter and the returned data as the second parameter. In this case, the data is the id of the newly inserted link.

Click the “Run” button and see how Meteor Methods work.

Get hands-on with 1200+ tech skills courses.