Meteor: Simplifying the process of deleting two documents from separate collections in MongoDB with just one click

There is a possibility that some "news documents" (from one collection) may contain an image (from another collection I'm using cfs:standard-packages and cfs:filesystem for file handling).

Here is an example of a news document in the Mongo Database:

{
    "_id" : "75d5nZGitsLvo5APM",
    "title" : "News with Image",
    "description" : "This news entry includes an image",
    "type" : "news",
    "createdAt" : ISODate("2016-01-31T15:46:01.334Z"),
    "coverImageId" : "js5k88PuPeKJwRqcq"
}

And here is an image document:

{
    "_id" : "js5k88PuPeKJwRqcq",
    "original" : {
        "name" : "amir_rahbaran.jpg",
        "updatedAt" : ISODate("2014-02-14T14:56:36.000Z"),
        "size" : 41614,
        "type" : "image/jpeg"
    },
    "uploadedAt" : ISODate("2016-01-31T15:45:58.060Z"),
    "copies" : {
        "images" : {
            "name" : "amir_rahbaran.jpg",
            "type" : "image/jpeg",
            "size" : 41614,
            "key" : "images-js5k88PuPeKJwRqcq-amir_rahbaran.jpg",
            "updatedAt" : ISODate("2016-01-31T15:45:58.000Z"),
            "createdAt" : ISODate("2016-01-31T15:45:58.000Z")
        }
    }
}

The issue at hand: When an admin deletes a news entry, only the news document gets deleted while the images remain in the database. The coverImageId in the news document and the _id in the image document are both identical.

This is my template.js code:

Template.adminNewsEventsList.events({
    'click #js-delete-ne': function (evt,template) {
        evt.preventDefault();
        var deleteConfirmation = confirm('Are you sure you want to delete this entry?');
        if (deleteConfirmation) {
            Images.remove({_id: "coverImageId"});
            NewsEvents.remove(this._id);
        };
    }
});

And this is my template.html code:

<template name="adminNewsEventsList">
    <div class="container">
        <div class="col-md-6 col-md-offset-3">
            {{#each newsEventsData}}
            <ul class="list-group">
                <li class="list-group-item">
                <a title="Edit" id="js-edit-ne" href="{{pathFor route='adminNewsEventsEdit'}}">{{title}}</a>
                <!-- edit button -->
                <a title="Edit" id="js-edit-ne" class="btn btn-primary" href="{{pathFor route='adminNewsEventsEdit'}}"><i class="fa fa-pencil-square-o"></i></a>
                <!-- delete button -->
                <a title="Edit" id="js-delete-ne" class="btn btn-danger" href="#"><i class="fa fa-trash"></i> </a>
                </li>
            </ul>
            {{/each}}
        </div>
    </div>
</template>

Any assistance on this matter would be greatly appreciated.

Answer №1

Just as I was about to click the submit button, the solution suddenly came to me. I believe it's worth sharing in case it helps someone else.

The following line:

Images.remove({_id: "coverImageId"})
needs to be updated to:

Images.remove({_id: this.coverImageId})

I hope this proves useful to someone out there.

Any further suggestions are welcomed.

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

Expansive full screen image proportions

Is there a way to showcase an image on the entire screen without distorting it, while maintaining its aspect ratio in either HTML or Javascript? The desired outcome is for the image to be centered and: - Have a height of 100% and a width of x% (where "x" ...

result of Hive query with no data

I recently created an external Hive table using a tweets json file exported from Mongo DB. However, I have noticed that when I attempt to select more than one column from the hive table, the retrieved results are not properly formatted. Some columns appear ...

What could be causing my callback function to fail when used within a nested function?

I am currently utilizing the callback function in conjunction with Socket.io as shown below: loadData(callback) { var client = new SyncClient(this.socket, this.project); this.client = client; //From my data function client.on("connected", () => { ...

I encounter a problem every time I attempt to establish a connection with my MongoDB database

As a beginner in utilizing full stack development to create an application, I attempted to establish a connection that allows the client side to connect to my MongoDB database. Below is the code snippet from my server.js file: console.log("Server running ...

Combining JSON array objects in Vanilla Javascript to create a nested array based on a shared value

I have been searching for a solution to address my specific issue but have not found an exact match. If there is a similar question, please provide a link to the solution. I am looking to merge an array of objects that share a common value using vanilla J ...

The Javascript executor in Selenium is delivering a null value

My JavaScript code is causing some issues when executed with Selenium's JavascriptExecutor. Strangely, the code returns null through Selenium but a value in Firefox developer console. function temp(){ var attribute = jQuery(jQuery("[name='q& ...

Template for developing projects using JavaScript, HTML5, and CSS3 in Visual Studio 2013

After recently downloading Visual Studio 2013 Express for Web, I am struggling to figure out how to deploy projects that only consist of JavaScript, HTML5, and CSS3. Despite searching online for JavaScript templates and even trying to download Visual Stu ...

Is it possible to read an XML response as a stream using Ext JS?

Requesting an XML response can sometimes result in a slow completion time due to certain constraints. Despite this, the data begins returning quickly. I am wondering if it is feasible to read the response stream in Ext JS before it is fully complete. My u ...

Preventing Repetition in an HTML List using JavaScript

My HTML list is populated with values from JSON, and I have a button on the page. <button onclick="printJsonList()">CLICK</button> This button triggers the following JavaScript function: function printJsonList(){ console.log(ctNameKeep); ...

Is it allowed to use an ID as a variable identifier?

One method I often use is assigning a variable with the same name as the id of an element, like this: randomDiv = document.getElementById("randomDiv"); randomDiv.onclick = function(){ /* Do something here; */ } randomDiv.property = "value"; This tech ...

Determining the spatial capacity of a mesh using ThreeJS surpasses the volume of its bounding box

Issue at Hand: The challenge lies in the fact that the bounding box volume is turning out to be smaller than the volume calculated from the mesh. Attempts So Far: To begin with, I computed the volume of a bounding box using the following code: //loaded ...

Importing a JS class within a Vue.js script tag

I'm attempting to incorporate a JS file into the Vuejs script but for some reason, it's not working as expected. JS file class Errors { constructor() { this.errors = {}; } get(field) { if (_.has(this.errors, 'errors.' + ...

Retrieve information utilizing a where clause in a relational database model

Currently, in loopback 3.0, my goal is to retrieve data from multiple relational models while applying a where clause on one of the relations. Displayed below is an example of the JSON for the models: modelA.json { "properties": { &q ...

Adjusting camera orientation and field of view using trackball manipulation controls in THREEJS

Manually setting the position and fov of the perspective camera in THREE.JS is working as expected for me. However, when I try to interact with the scene later using the TrackBall Controls, it just shows a black screen with no errors. Check out this JS Fi ...

``I'm having trouble getting the onchange event to function properly in a customized

After following a tutorial, I successfully created a custom select dropdown using the provided link. https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select However, I am facing an issue with the onchange event not working for the select ...

Prevent form submission without JavaScript

While the issue is easy to grasp, it poses a challenge in implementation. I am encountering clients who disable their browser's Javascript by default, causing complications on my website. This is because my website sends ajax requests upon form submis ...

Steps for displaying a customized view within an NPM module:

Given that pushAsset prohibits loading external resources, I am interested in displaying this template/script from my NPM module: views/tag.html <script async src="https://www.googletagmanager.com/gtag/js?id={{ data.gid }}"></script> NPM mod ...

Accessing geographical coordinates using Google Maps API with JavaScript

Hey there, I could really use your assistance. I'm looking to integrate a localization map on my website to track user locations. Any idea how I can go about doing this? Thanks in advance! ...

Inquiring about JavaScript's substring method in String.prototype

let vowels = "AEIOU"; let result = vowels.substring(0, 3); document.write(result); I'm puzzled as to why the output is AEI instead of AEIO. Is this due to the indexing starting from zero in programming languages? ...

Ways to retrieve an item from a series of successive arrays

I'm struggling to find a solution to my current issue. My goal is to retrieve the item at a specific index from a collection of separate arrays without merging them together. Typically, to access the 3rd item in an array, you would use: function get ...