MeteorJS insert function failing to add new data

After spending the last 4 and a half hours scouring the internet, I'm still stuck on why my insert method in my real time messaging app isn't working. It's not throwing any errors, it's just not actually inserting anything.

Here's the code snippet for it: JS client:

Template.input.events({
        "keypress .input": function(event, template){
            if(event.which == 13){
                event.preventDefault();

              var user = Meteor.user();
              var message = template.find(".input").value;
              alert(Meteor.call("insert", user.username, message));

              template.find(".input").value = ""; 

          }
      }
    });

JS Server:

Meteor.methods({
      'insert':function(username, message){
            Messages.insert({
                'message': message,
                'user': Meteor.userId(),
                'username': username,
                'timestamp': new Date()
            });
            return "success";
       },
      'find': function(){
            Messages.find({}, {sort: {timestamp:-1}});
      }
  });

HTML:

<template name="input">
    <div id="input">
        <input class="input" type="text" placeholder="Message..." id="message" />
    </div>
</template>

Even after checking the console, nothing seems to be getting added.

Answer №1

Your code is functioning correctly, and the data is being successfully saved in the database. As mentioned by jorjordandan and Michel, the issue may be related to your publications.

To troubleshoot this, consider adding some logging to track what is being stored. Since server methods have access to all collections, you can easily monitor the data being saved.

  'insert':function(username, message){
        var id = Messages.insert({
            'message': message,
            'user': Meteor.userId(),
            'username': username,
            'timestamp': new Date()
        });
        console.log('Inserted id: ' + id);
        var insertedMessage = Messages.findOne(id);
        console.log(insertedMessage);
        return "success";
  },

Additionally, consider revising how you handle usernames in the server method to prevent client-side manipulation. Instead of passing the username as a string, you could retrieve the user on the server side.

Meteor.user().username

Ensure that the user is logged in before using this method, or check if Meteor.user() returns undefined.

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

Issue with useEffect causing a delay in updating the state value

I'm facing an issue with a component that displays the number of people who have liked a book. The problem is, I can't seem to consistently get the correct result in my states. Here's the code snippet: ///Fetching the book details cons ...

Prevent tracking of campaigns in Google Analytics by not following tagged links from banners to a website

My website is connected to Google Analytics. I have banners on my site that link to external pages with tracking tags added to the URL: However, I am not seeing campaign statistics in the Traffic Sources - Campaigns section of my Google Analytics account. ...

Multiple file formats supported by Uploadify

I am trying to find a solution for having various file types in the jQuery plugin Uploadify. Consider this scenario: You want to open a file with a program of your choice. Starting with a default OS dialog, you can select different file types from a dropd ...

leveraging the static method in a JavaScript class

My dilemma is over which option would be quicker. Should I instantiate a new object from a class and use that, or should I utilize a class with static methods? export default class AuthServices { static async login (data) {} static async register ...

What sets srcset apart from media queries?

Can you explain the contrast between srcset and media query? In your opinion, which is more optimal and what scenarios are ideal for each? Appreciate it! ...

Show the user's input within a clickable button

I'm trying to create a functionality where I have an input field and a button next to it. When I type something in the input field and click on the button, I want the result to be displayed in another button. Here is what I have attempted so far: f ...

Troubleshooting a problem with selecting options in Jquery

Looking for assistance with a jquery script. I have a select dropdown that fetches a list of options via Ajax. When a user clicks on an option, if a certain variable equals 1, an HTML div is added. If the variable changes to another value, the HTML div dis ...

Include the model.obj file into the three.MESH framework

I am a beginner in three.js and I am developing an augmented reality application on the web to showcase plates of food. Currently, I have successfully displayed a cube. However, when I attempted to display a model.obj instead of using geometry and material ...

Is it necessary for Webpack to package all dependent node modules with the final bundle in production mode?

It's common knowledge that when we run npm run build, React scripts utilize Webpack to create a bundle by examining the entire dependency graph (following imports) and generating a bundle.js which is then stored in the dist/build folder for production ...

Having trouble with refreshing the div content when using jQuery's $.ajax() function

My goal is to refresh a div that has the id #todos after saving data in the database. I attempted to use .load() within $.ajax() $('.todo--checkbox').change(function () { let value = $(this).data('value'); $.ajax({ url: ...

Generating a File that Imports Components and Instantly Exports Them Once More

Having trouble with this code. Initially, I had: // file 1 import Box from '@/components/Box' import Popup from '@/components/Popup' const MDXComponents = { Box, Popup } // using MDXComponents somewhere in file 1 Now, to manage t ...

Issue with symbol not functioning on different device

There seems to be a display issue with the ...

dojo combobox with data loaded dynamically from JSON

I am facing an issue with populating a Combobox dynamically using a jsonRest from a cross-origin request. While I have managed to do it statically (if that's the correct term), I am struggling to implement it for multiple cases. This is just a small ...

React-Select for Creating a Dynamic Multi-Category Dropdown Menu

I am looking to incorporate react-select into my project for a multi-category dropdown list. Specifically, I need the ability to select only one option at most from each category. To better illustrate this requirement, consider the following example wher ...

Creating visual representations of class, organization, flow, or state diagrams using Vega or Vega-lite

I'm struggling to find an example of a state, class, flow chart, or org chart diagram created with Vega. Are there any available online? Vega seems like the perfect tool for this type of visualization, although it may be a bit complex. Without a star ...

Utilizing checkboxes to toggle the visibility of a div element with varying headings

By toggling a checkbox, I aim to show or hide the same div with a different heading. $('#cbxShowHide').click(function() { this.checked ? $('#block').show(1000) : $('#block').hide(1000); }); #block { display: none; bac ...

encountering a glitch while using console.log(util.format

Let me start by saying that I am fairly new to working with node.js. A friend of mine assisted me in writing the code snippet below. I have successfully installed the necessary packages search-google-geocode, csv-parser, fs, util, and async using npm. H ...

Pause the counter based on the data attribute containing multiple values

I have a collection of div elements, each with a unique data-attribute value. My goal is to display these values in the divs using JavaScript by incrementing a counter. const numbers = document.querySelectorAll(".number"); console.log(numbers); let c ...

Inject "incorrect" information using jQuery

I am dealing with the following constellation: <dl> <dt>Content</dt> <dd>123</dd> <dt>Content</dt> <dd>123</dd> <dt>Content</dt> <dd>123</dd> </dt> ...

use javascript or jquery to conceal the textbox control

Looking to conceal a textbox control using javascript or jquery. I attempted the following code: document.getElementsByName('Custom_Field_Custom1').style.display="none"; Unfortunately, I received an error in the java console: document.getEle ...