Using Meteor: Sharing a variable among all methods in Meteor

Just dipped my toes into the world of Meteor and managed to create a simple turn-based multiplayer game.

When player 2 joins the game, I update the Game collection using a Meteor.method. However, when I try to retrieve that update in another Meteor.method, I have to use Games.find() again to access the updated value.

Is there a way for me to store the current Game instance so that all my Meteor.methods can access it?

If this were on the client-side, I would typically use reactive-vars, but that doesn't seem to be an option here.

Edit:

Meteor.methods({
    startGame: function() {
        return Games.insert({
            players: [{
                _id: Meteor.userId()
            }]
        });
    },
    joinGame: function(game) {
        return Games.update({
            _id: game._id
        }, {
            $set: {
                endsAt: new Date().getTime() + 10000
            },
            $push: {
                players: Meteor.userId()
            }
        });
    },
    getDataFromGame: function() {
        // Struggling to find a way to access data from the game inside other methods 
        // without having to use Games.find
        // Any suggestions?
    }
});

I attempted to save the current game within the methods object, but it didn't reactively update. Not sure what steps to take next.

Answer №1

Instead of retrieving a game through a Meteor.call(), it's better to simply display the games that the user has joined.

Meteor.publish('myGames',function(){
   return Games.find({ players: { $elemMatch: { _id: this.userId }}});
});

On the client side:

Meteor.subscribe('myGames');

I would like to mention, in your startGame function, the players key includes an array of objects like {_id: Meteor.userId()}, but in another part of the code for startGame, the same key only contains an array of user _ids. It's advised to choose one format and stick with it. The simpler array form works well, in which case your publish function should be:

Meteor.publish('myGames',function(){
   return Games.find({ players: this.userId });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to fully eliminate the Pixi renderer, stage, and all associated assets

I am currently faced with a challenge of mounting and unmounting a Pixi stage using React without relying on react-pixi. Upon re-mounting the component, I encounter the following error: Uncaught Error: Resource with name "cupCake.png" already exists i.ad ...

Error encountered in Firefox: THREE.js throws a TypeError because 'global' is undefined

After attempting to integrate three.js into my code as a standalone script without using webpack, browserify or requirejs, I encountered an issue. My setup involves loading an external Angular app and extending it, but now I need my own version of THREE.js ...

Can native types in JavaScript have getters set on them?

I've been attempting to create a getter for a built-in String object in JavaScript but I can't seem to make it function properly. Is this actually doable? var text = "bar"; text.__defineGetter__("length", function() { return 3; }); (I need th ...

Attempting to transfer a property from one page to another using the Link component in NextJS

Currently, I have a page containing six Link elements that are meant to redirect to the same destination but with different props based on which link is clicked. To pass props, this is how I've implemented it: <Link href={{ pathname: '/pro ...

The data retrieved from the backend is being stored in an object, however, it is not directly accessible through

After receiving data from the backend and storing it in an object, I am facing an issue where trying to print it using object properties shows undefined values. Here is a snapshot of my output: view image here Snippet of my code: this.documentService.getD ...

JavaScript - Asynchronous JavaScript and XML

function sendRequest(settings) { settings = { type: settings.type || "POST", url: settings.url || "", timeout: settings.timeout || 5000, onComplete: settings.onComplete || function(){}, onError: settings.onError || function(){}, onSuccess: set ...

PHP script encountering server error due to JavaScript file upload

I've been going crazy for the past month trying to create a page that can asynchronously submit a PDF to our server. Although I have experience in programming, I have never ventured into web development, PHP, or JavaScript before. Here is the JavaScr ...

Is MongoDB caching its collection in memory?

Utilizing mongoDB for storing a set of polygons and executing $geoIntersects queries to determine the polygon containing a specific point. My mongoose Schema is structured as follows: var LocationShema = mongoose.Schema({ name: String, geo: { ...

The button's background color remains the same even after clicking on it

In my exploration of Vue.js, I decided to create a simple project to grasp the concept of class binding. I wanted to add functionality to each button component, so that when a button is clicked, it would change its color or background color to something ot ...

Leveraging greensock with browserify

Having trouble integrating TweenLite with browserify. I'm still learning about CommonJS and could use some help. Installed gasp v1.13.2 via Bower, including it like this: var TweenLite = require("../../bower_components/gsap/src/minified/TweenLite.mi ...

Integrating a <script></script> tag into the content method of fancybox2: A step-by-step guide

Currently, I am attempting to include a JavaScript content within the content method of fancybox. <script> $('#streaminput').on("click", function() { $('#streaminput').fancybox({ width : '95%', height ...

Angular routing and parameters are not functioning as expected

In my code, I have implemented the following controller: app.controller('ObjectBoardCtrl', ['$scope' , '$rootScope' , '$routeParams' , function($scope , $rootScope, $routeParams) { $scope.selectedObjectId = $ ...

submit multiple images simultaneously

I'm attempting to upload multiple photos simultaneously using XMLHttpRequest. if(files.length <= 6) { for(var i = 0; i < files.length; i++) { var formData = new FormData(); formData.append('action', 'upload ...

Building a feedback mechanism with HTML, JavaScript, and MongoDB

I had an idea to develop an employee feedback system that could gather feedback and store it in my MongoDB database. I have included the backend and frontend code below, but unfortunately, I ran into an error: Failed to submit feedback. Please try again ...

Observables waiting inside one another

I've encountered an issue where I need to return an observable and at times, within that observable, I require a value from another observable. To simplify my problem, let's consider the following code snippet: public dummyStream(): Observabl ...

Encountering an issue with React Router v6 where calling `history.push('/')` results in an error of "undefined (reading 'pathname')" - the URL changes, but the page remains unchanged

Having an issue altering the page within a Redux Thunk action creator to redirect the user back to the homepage after form submission Although the URL changes when the action creator is triggered, the page itself remains the same Unable to utilize Browse ...

Empower your presentations with slick cloning technology

I am facing an issue with my slider that I cannot seem to resolve. Currently, I am using slick to display 3 slides, but only the center one shows all the content. To achieve a continuous infinite slider effect where all slides appear in the center, I need ...

Struggling to make JavaScript read JSON data from an HTML file

I am currently working on developing a word search game using django. One of the tasks I need to accomplish is checking whether the entered word exists in a dictionary. To achieve this, I have been converting a python dictionary into JSON format with json. ...

Transforming a decimal number into binary base 2 manually in Javascript without using pre-defined functions

As a newcomer to coding and Javascript, I have been given an assignment that requires me to convert base 10 numbers to binary without using specific built-in methods in Javascript (such as alert(a.toString(16))). The constraints are that I can only use loo ...

Transforming Jquery into vanilla JavaScript and sending a POST request

Hey everyone, I'm in the process of converting Jquery code to pure javascript and encountering some difficulties with the following snippet: $.post('ajax_data',{action:'service_price',service:service,quantity:quantity,dripfeed:drip ...