Error encountered while updating Meteor collection

I'm having trouble with my code while working through the Discover Meteor book and building a small app to deepen my understanding of the concepts:

Template.panelCM.events({
'click .editProductsCol': function(e) {
    e.preventDefault();
    if (confirm('Edit?')){

    var currentProduct = this._id;

    var productOptions = {
        name: $(e.target).find('[name=productName]').val(),
        description: $(e.target).find('[name=productDescription]').val()
    };

    Products.update(currentProduct, {$set: productOptions}, function(error) {
        if (error) {
            alert(error.reason);
            throwError('Error');
        } else {
            Router.go('tabPage');
        }
    });
}},

'click .deleteProductsCol': function(e) {
    e.preventDefault();

    if (confirm("Delete?")) {
        var currentProduct = this._id;
        Products.remove(currentProduct);
        Router.go('tabPage');
    }
}});

The delete functionality is working fine, but I'm facing an issue with the update operation. After submitting, I receive the following error message:

MongoError: '$set' is empty. You must specify a field like so: {$mod: {<field>: ...}}

This is how my template looks:

<template name="panelCM">
{{#each products}}
    <div class="col-xs-12 col-sm-6 col-md-6 mainCol">
        <img src="../{{image}}"/>
        <input type="text" name="productName" id="productName" class="form-control" placeholder="{{name}}">
        <textarea name='productDescription' id="productDescription" class="form-control colP" rows="10"
                  placeholder="{{description}}" style="color: black"></textarea>
        <button type="submit" class="btn btn-lg btn-success form-control editProductsCol">Edit</button>
        <button type="submit" class="btn btn-lg btn-danger form-control deleteProductsCol">Delete</button>
    </div>
{{/each}}</template>

I believe I may have misunderstood the purpose of the productOptions variable. It seems like I am creating an object that captures the values from specific HTML elements and passing it to the Products database for updating. I'm unsure if I need to also use an ID in my template, as seen in the book, since I can locate the correct element using the 'name' attribute (unsure about the technical term for this). Additionally, should the 'name' and 'description' fields in productOptions match the corresponding fields in my database?

Answer №1

When using $.find, it searches through the descendants of the DOM element on which it is called. If you call it on an element that has no children, like the edit button in this case, it will not find anything and the .val() method will return undefined. MongoDB is giving an error because both fields are being set to undefined, which doesn't make sense. Try using the following approach instead:

'click .editProductsCol': function(e, template) {
    e.preventDefault();
    if (confirm('Edit?')) {

    var productOptions = {
        name: template.$('[name=productName]').val(),
        description: template.$('[name=productDescription]').val()
    };

    Products.update(this._id, {$set: productOptions}, function(error) {
        if (error) {
            alert(error.reason);
            throwError('Error');
        } else {
            Router.go('tabPage');
        }
    });
  }
},

Understanding Meteor

Let's break down the code. In a Meteor event handler, this refers to the model, so this._id (assigned to currentProduct) gives you the id of the document you want to update.

Now that we know which document to update, let's figure out how and what to update it with. The second parameter in the event handlers is the template instance, containing a $ property for querying form data within the template's context.

Next step is calling the update method on the Meteor.collection. As per the documentation, it requires the _id as a selector, a modifier object, and a callback. Your modifier should include the $set property to specify which fields to modify.

Lastly, I recommend using value attribute instead of placeholder for input elements unless there's a specific reason not to. Placeholders are just visual hints and do not affect form content directly.

    <input type="text" name="productName" id="productName" class="form-control" value="{{name}}" placeholder="Enter the name">
    <textarea name='productDescription' id="productDescription" class="form-control colP" rows="10" value="{{description}}" style="color: black" placeholder="Enter a description"></textarea>

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

How can I maintain the consistent speed of the Javascript timer even when the .deck is clicked?

Currently, I'm working on creating a memory card game. In this game, the deck of cards is represented by the class .deck. Strangely enough, every time I click on a card, the timer starts to speed up instead of keeping a consistent pace. How can I tack ...

Why are Ajax calls returning 404 in Google Cloud Platform but working perfectly on local servers?

I recently came across a fantastic repository that offers a Java REPL directly in the browser. I decided to fork it and deploy it as a Google Cloud app to enhance its security with HTTPS. Everything seems to be working smoothly, except for one issue: Unf ...

Apply the jQuery class to each JSON result to style it with CSS

I'm currently working on enhancing the filter options in my online store by incorporating color coding. I have successfully saved the color codes and now retrieve them through json. My goal is to add these color codes to the parent class above the inp ...

Add a click event listener to the body element using a button click, without causing it to trigger

What is the current situation: A button is clicked by the user The menu opens (list items display = block) The function to close the menu is connected to the <body> The function to close the menu is immediately triggered, causing the menu to close ...

Setting up a software from a GitHub source

My issue arises when attempting to install a particular package of mine with the version specified as a specific git branch. The problem occurs because the repository does not contain the dist folder, which is required by my npm package. Here is the metho ...

Is it time for a countdown clock?

Looking to create a Countdown timer? Upon page load, the clock initiates a countdown. Once it reaches zero, it will automatically redirect the browser to a new page. Came across this resource, however, it did not fulfill my needs: ...

Utilizing the openweathermap weather widget on a Leaflet map within the R programming

I am attempting to incorporate custom weather tiles onto a leaflet map within a Shiny application by utilizing the leaflet-openweathermap JavaScript library found here. As someone who is not well-versed in JavaScript, I am encountering difficulties with re ...

Tips on disregarding hyphens in values when querying MongoDB documents

Greetings! I'm currently facing an issue with my data collection where I have values stored as strings with hyphens between words. For example: "item:'e-commerce'" My main query is whether there are any settings in Mongo that would allow it ...

Blending MapLibre GL JS with ThreeLoader3dTiles

After much trial and error, I have successfully implemented a code snippet that displays a Cesium 3D tiles model. This code effectively sets up a basic scene, loads the Cesium model, and integrates it into the scene. import { useEffect, useRef, useState } ...

Why won't the button's color change when I try clicking on it?

I am currently learning vue and facing some challenges. The code I have is supposed to change the button color when clicked, but it's not working as expected. Any advice on how to fix this issue would be greatly appreciated. Thank you! let app = ...

Controlling Vue data with an external JavaScript file

I'm facing an issue with manipulating Vue data through an external js file that I've exported a function from. Despite my efforts, I haven't been able to achieve the desired outcome. Here's what I have attempted so far: My import state ...

What should you do when the server is taking a while to respond?

I am in the process of creating a webpage that involves interactions between users, and I could use some guidance. Let's consider this hypothetical scenario: Client A visits a 'public' webpage and clicks a button. Client A then waits for a ...

Obtain the current time for a specific user

I'm currently struggling with obtaining the accurate 'trusted' user time, in order to prevent any cheating through manipulation of their computer's clock. Whether I utilize a basic date object, moment timezone, or even Google timezone ...

Ways to resolve the problem of connecting Provider with my store and efficiently transmitting data to components in my Redux-React application

Encountering an error that reads: Uncaught Error: Could not find "store" in either the context or props of "Connect(WebShop)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(WebShop)". Despite havin ...

What is the reason for the directive being available in $rootScope?

Currently, there doesn't seem to be a major issue but it has sparked my curiosity. I have a straightforward directive that, for some unknown reason, is accessible within $rootScope. JAVASCRIPT: (function(){ var app = angular.module('myAp ...

What is the best approach: creating a single MongoDB model or splitting it into two

Currently, I am in the process of developing a mean stack application that will allow users to both read and write reviews on various products. The design involves categorizing reviews by product. A user will first access a page showcasing all products av ...

Display the HTML/CSS layout following the JavaScript window.open action

Encountering issues with printing output in an opened window using JavaScript. I'm creating a new document through window.open and including CDN links to Bootstrap files. While everything appears fine in the opened window, when attempting to print (XP ...

Unable to fetch an identification number using swfupload

I seem to be encountering an issue with retrieving an echoed AJAX response through SWFupload. After uploading a file, the account.php?action=uploadphotographs echoes the number 37, which should update the text field hidFileId with this data. I am uncertain ...

The addListener method in Google Maps iterates n times for a specific number of repetitions

When looking at the code below, the GetPropBasedOnRadius(); method loops for a certain number of times. I want to call that method only when the dragging event is completed. However, I am unsure how to do this. Any assistance on this matter would be great ...

Any tips on how to retrieve the data from an AJAX request using vanilla JavaScript?

After successfully implementing my first AJAX call last week, I am now faced with a new challenge. This time, I need to not only change something onSuccess but also access the returned data. <script type="text/javascript"> function showMessage(j ...