Is writeConcern not being returned by MongoDb's deleteOne function?

I have a function that deletes a specific document in MongoDb based on an id match. Below is the code snippet.

deletePoll: function(db, user_id, callback) {
        db.collection('polls').deleteOne({
                _id: user_id
            },
            function(err, result) {
                if (err) {
                    console.log(err);
                }
                if(result){
                    console.log(result);
                }
            });
    }

However, the above code only logs a large object when the if(result) condition is met. The object it logs is detailed below.

{ result: { ok: 1, n: 0 },
  connection: 
   EventEmitter {
     domain: null,
     ...
     ...
     ...
     ...
     ...
     ...
     ...
     ...
     ...
     ...
     ...
     ...
     ...
     ...
     ...

Even after manually checking the mongo console, the document remains undeleted. I'm puzzled as to why the document is not being removed. Additionally, why is the writeConcern object not showing up? Why is this extensive object being returned instead?

Answer №1

It appears that the issue may lie in the user_id parameter. Are you passing in a String to that parameter? If so, you may need to use { _id: new ObjectId(user_id) } as the first argument in the deleteOne function. The output you are receiving shows deletedCount: 0, indicating that it is trying to match the string user_id to the _id of a document, which is of type ObjectID. Comparing a string to an ObjectID may be causing the issue. You can refer to the ObjectId documentation for more information.

Additionally, you should review the deleteOne documentation which suggests passing in a filter object, options object, and then your callback. It seems that you may be missing the options object. You could try passing in null or {} as your second parameter before the callback.

Based on the db documentation, your issue could be related to a timing problem. If you are using strict mode with db.collection('colName'), it also requires a callback. You could try the following approach:

deletePoll: function(db, user_id, callback) {
        db.collection('polls', { strict: true }, function (err, col) {
            if (err) {
              // handle error
            } else {
              deleteUser(col);
            }
        });    
    }

function deleteUser(col) {
    col.deleteOne({
        _id: user_id
    },
    function(err, result) {
        if (err) {
            console.log(err);
        } else {
            console.log(result);
        }
    });
}

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

Send information using AJAX's POST method

Can an image file be uploaded using the jQuery ajax post method? Will it work if the file data is simply placed in the POST request's 'data' parameter? I am working with the django framework and this is my initial attempt: $('#edit_us ...

Is there a way to specifically remove only the last row from a table?

Recently, I encountered a problem with my JS code that adds and removes table rows based on user interaction. Adding rows functioned perfectly, but the issue arose when attempting to delete rows. Instead of deleting only the last row as intended, all rows ...

Where is the best place to implement HTML form validation: on the frontend or backend?

Is it important to validate all values before submitting the form to the backend server, as mentioned in the title? ...

The toggle in the dialog box refuses to submit the information

I am facing an issue with a dialog box that I am displaying using the jQuery .dialog() function. The dialog box contains a button that I want to use to post back to another page, but for some reason, it is not working as expected. I have tried setting the ...

Exploring a JSON tree recursively and combining its branches

I am attempting to navigate a recursive json tree (json2) and combine it with another json (json), matching identifiers. It's important to note that when objects are present, they may contain either objects or object, but the identifier will always be ...

The functions deleteOne, findOneAndDelete, and findOneAndRemove all remove a pair of documents

I am currently working with mongoose and mongodb 4.2.8, along with Node.js 14.4.0. My goal is to locate the initial document that matches both the first name and last name, and then remove it. However, I've noticed that when using findOneanddelete, de ...

Random sequencing of the commands

Whenever I call the Details function, it returns empty details because the function executes before retrieving data from the json file. What is the best way to fix this issue? app.controller('loginCtrl',function($scope,login){ $scope.user=login ...

Trigger a simulated click on an element using code when the Enter key is pressed in an input field

Here is the HTML code snippet: <div class="container"> <div class="row d-none d-md-block d-xl-none" id="PrescriptionTitle"> <div class="col-sm-6"> <span for="" class="text-left">Brand Name</span> < ...

Issue encountered when attempting to utilize Next-Auth alongside Credentials Provider to authenticate within a pre-existing system

I am currently utilizing the Next-Auth Credentials provider for authentication purposes through our existing API. Following the guidelines provided at https://next-auth.js.org/configuration/callbacks the code snippet used is as follows: callbacks: { ...

In dire need of assistance with dividing an array into a menu using JavaScript before my brain implodes

With the usage of Javascript, I am dealing with an array structured as follows: [{"id":171, "children": [{"id":172}, {"id":170}, {"id":173}]}, {"id":174}, {"id":175}] This array is created from a nestable jQuery list. Now, I have the require ...

Prevent tooltip text from appearing when a button is disabled in an angular application

As a beginner in UI development, I have a requirement for my Angular application. I need to enable and disable a button based on certain conditions. The tricky part is that I want to display a tooltip only when the button is enabled. I have managed to chan ...

The combination of several JOIN operations and GROUP BY is leading to unexpected results with the ORDER BY clause

SELECT msg.msgFrom, mem.memberID, mem.memberFirstName, mem.memberLastName, msg.msgJobID, msg.msgMessage, msg.msgRead, job.jobDescription FROM messages msg JOIN members mem ON msg.msgFrom = mem.memberID JO ...

Unable to locate node module when using Npm.require

I've been attempting to utilize the Npm.require method in order to access the ldapjs module for client authentication. Unfortunately, I'm encountering the following error message: var ldap = Npm.require('ldapjs'); Error: Cannot find ...

Guide on assigning a callback function in JavaScript

In this code snippet, I am initializing a new object variable and passing an object as an argument: const newObj = new customObject({ first : $('#fname').val(), last : $('#lname').val(), fn : function() { alert(this ...

Building a node.js form that supports multiple images and input fields

After spending nearly an entire day trying to resolve this issue, I am seeking some assistance. Within my project, I have implemented a feature called "Add Product" which is functioning just as I envisioned it. However, I would like users to have the abili ...

Utilizing HTML5 to Access and Update custom data attributes

I have implemented the following code: var activeFilter = $('<li></li>').data('input-id', 'mycustomId'); $('#container').append(activeFilter); Now, I am faced with the challenge of retrieving a specific ...

Issue with adding object to array using forEach() function

As I navigate my way through an express route, I am puzzled as to why the "purchasedCards" array turns out empty after going through these database calls. Despite successfully gathering all the necessary information from various DB Queries and placing it i ...

Experiencing a blank array when using filtering/search text in a Nodejs application with MongoDB

I am experimenting with search functionality in a MongoDB database using Node.js. However, my result array is always empty. I have shared my code here and would appreciate some assistance in identifying the issue. Whenever I perform a search, I end up with ...

Prevent ng-click functionality for markers and infowindows on an Angular map

Currently, I am utilizing angular map and have bound an ng-click event to it which triggers a dialog window to open. However, I am facing an issue where I want to disable ng-click for markers and infowindows. This problem did not arise when I was using pla ...

Is it possible to extract the selected indexes of all select menus in my HTML and assign them to various arrays of my choosing? I find myself writing a lot of code just for one select menu

In order to determine which TV character the user most closely resembles based on their answers to a series of questions, I have created a function. However, my current code is inefficient when it comes to handling multiple select menus! I am considering i ...