Deleting a document in Mongo with the use of an object as a value

Hello, I'm struggling with deleting a document from my MongoDb using an object.

Let me explain:

const removeDocument = function (db, callback) {
  // Access the collection of documents
  const collection = db.collection(documentName)
  // Delete the specified document
  console.log(trimNameToDelete)
  collection.deleteOne({Video_trim: trimNameToDelete}, function (err, result) {
    assert.equal(err, null)
    assert.equal(1, result.result.n)
    console.log('Document removed')
    callback(result)
  })
  fs.unlink('./public/videos/cut-videos/' + documentName + '/' + trimNameToDelete.trimName + '.mp4', (err) => {
    if (err) {
      console.log('Failed to delete local image: ' + err)
    } else {
      console.log('Local image successfully deleted')
    }
  })
}

Where the value of trimNameToDelete is:

{"trimName":"cut2","startTime":"00:00:05","endTime":"00:00:15"}

and the document in MongoDb looks like this in the shell:

{ "_id" : ObjectId("5abe67897a9b9e0933c64acd"), "Video_trim" : { "trimName" : "cut2", "startTime" : "00:00:05", "endTime" : "00:00:15" } }

The error message I'm receiving is:

AssertionError [ERR_ASSERTION]: 1 == 0

Due to technical limitations, the Id cannot be used for deleting.

Answer №1

I have identified the issue – I needed to properly parse the trimNameToDelete. It was a silly mistake on my part as I was passing it as a string.

const deleteTrimByName = function (db, callback) {
  // Access the collection of documents
  const collection = db.collection(documentName)

  console.log('>>>>>' + trimNameToDelete)
  collection.deleteOne({Video_trim: JSON.parse(trimNameToDelete)}, function (err, result) {
    assert.equal(err, null)
    assert.equal(1, result.result.n)
    console.log('Document removed successfully')
    callback(result)
  })
  fs.unlink('./public/videos/cut-videos/' + documentName + '/' + JSON.parse(trimNameToDelete).trimName + '.mp4', (err) => {
    if (err) {
      console.log('failed to delete local image:' + err)
    } else {
      console.log('successfully deleted local image')
    }
  })
}

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 preventing the function from successfully compiling text from various files that are uploaded using the HTML5 file reader into an array?

My current challenge involves attempting to upload two text files using the HTML 5 file reader. While I can successfully get the files into an array, encountering difficulty arises when trying to return that array from the function. One solution could be ...

Data Filling and Consolidating in MongoDB

Recently, I inquired about a similar issue here: Mongoose/Mongodb Aggregate - group and average multiple fields I am attempting to utilize Model.aggregate() to determine the average rating of all posts based on date and then further categorized by specifi ...

Do you think my plan to develop an HTML parser from the ground up will be successful?

My goal is to enhance my skills by building an HTML parser. The basic idea I have in mind includes: Defining the tokenization using regex. Taking a string of HTML as input. Iterating through the HTML string. Storing details about each token, such as cont ...

The AJAX callback is unable to access the method of the jQuery plugin

I have a scenario where I am fetching data from an AJAX response and attempting to update a jQuery plugin with that value within the success callback: $.ajax({ url: '/some/url', type: 'GET', dataType: 'json', succ ...

Extracting Querystring Value in C#

When using the code below to set the iframe src with JavaScript, everything works as expected. However, in the C# code behind, I am receiving the query string in a format like this: id=Y&amp%3bcust_id=100&amp%3. Is there a way to simplify this? v ...

Is it possible to duplicate a response before making changes to its contents?

Imagine we are developing a response interceptor for an Angular 4 application using the HttpClient: export class MyInterceptor implements HttpInterceptor { public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<an ...

What is the best way to transform an HTML <script> tag into React code?

I am new to the world of JavaScript and React. Can someone help me convert the script below into a React component? <div id="SOHUCS" sid="xxx"></div> <script charset="utf-8" type="text/javascript" sr ...

Issue encountered when upgrading from Angular 4 to Angular 5: Module '@angular/router' is not found

I recently made the switch from angular 2 to angular 5. However, after the upgrade, I encountered some errors in my ts file. Should I remove @angular/core and @angular/router in angular 5? Here is a snippet of my package.json post-upgrade. Below are the de ...

What is causing the newly generated input tags to disappear from the page?

I'm having an issue where my code successfully creates new input tags based on user input, but they disappear shortly after being generated. What could be causing this to happen? <form> <input type='text' id='input' /> ...

What is the best way to reference a nested jQuery variable, whether global or local, within an HTML document

I've been working on this problem for days with no success. Any help would be greatly appreciated. I'm trying to call a variable from nested jQuery into HTML. The variable is named "PROBLEM". Even after trying to make it global, any updates made ...

The error message "Uncaught ReferenceError: req is not defined with [email protected]" indicates that the variable

Discovered a helpful post that seems to address the problems. https://github.com/angular/angular-cli/issues/8359 I'm unsure about the steps to take next to resolve this issue. Can anyone clarify? Could you please advise on which version of Angular ...

Issue with Angular dropdown menu not showing the initial option

I am trying to set up a drop-down menu with the first item in the list appearing after it has been sorted by 'name' using the code snippet below: <h2 class="presentation site is-input-header">Site</h2> <div class="modal-select-ele ...

Performing a MongoDB aggregate operation to swap out a set of IDs with their corresponding objects from an array located within the same document

In my collection, I have a variety of documents that look like this: [{ id: 1, name: 'My document 1', allItems: [{ id: 'item1', name: 'My item 1' }, { id: 'item2', name ...

Manipulating the visibility of components by toggling on click events according to the existing state in ReactJS

Disclosure: I am still getting familiar with ReactJS I'm currently working on incorporating a dialog window for selecting a country/language on the initial page of my application. Here's the concept: There's a small flag button in the to ...

Using $.ajax() to store data in the database

Is there a way to save dynamically generated elements from my application.js file into the database? Would the code be similar to this example?: $.ajax({ type: "POST", data: { title: 'oembed.title', thumbnail_url: 'oembed.thumbnail_ur ...

Java - Evaluating the Date(0) retrieved from a null database entry

My task is to retrieve all records from a selected collection where the something_date field is null, but in MongoDB, the value for this field is shown as "something_date" : null. However, when retrieving these null values for something_date, an Epoch date ...

Error message: Laravel unable to locate requested page

Attempting to make a post request using AngularJS in Laravel, I encountered the following error message: Oops! The page you are trying to access could not be found. JAVASCRIPT app.controller('main',['$scope','$http',&apos ...

Load a Javascript file from the local server

My website is encountering a problem when trying to load a script from a localhost server. The error message displayed is PROTOCOL ERROR: https://localhost:4200/script/test.js net::ERR_SSL_PROTOCOL_ERROR Here is the code snippet causing the issue: <!DO ...

I prefer the user not engage with the background when the jQuery dialog is displayed

When a user clicks on an external link, the jQuery UI dialog box will appear with "ok" and "cancel" buttons. Upon clicking "ok," the user should be directed to the external site. Although everything is functioning correctly, there is an issue with the mod ...

How to display currency input in Angular 2

Is there a way to dynamically format input as USD currency while typing? The input should have 2 decimal places and populate from right to left. For example, if I type 54.60 it should display as $0.05 -> $0.54 -> $5.46 -> $54.60. I found this PLUN ...