ahmetkca
ahmetkca

Reputation: 637

MongoDB How to catch errors in deleteMany

I have looked at MongoDB documentation for deleteMany() but it seems the only error it throws is WriteConcernError.

I am using Insomnia to make my requests.

Here is my request:

DELETE HTTP://localhost:5000/api/users/delete/usernames?usernames=["a","b","c"]

As you can see I have an array in query string so I pass that to my function

@ user.controller.js

function _deleteByUsernames(req, res, next) {
    userService.deleteByUsernames(JSON.parse(req.query.usernames))
        .then(() => res.status(200).json({"message": "User(s) successfully deleted!"}))
        .catch(err => next(err));
}

@ user.service.js

async function _deleteByUsernames(usernames) {
    try {
        console.log(usernames);
        await User.deleteMany({username: {$in: usernames}});
    } catch (err) {
        throw err;
    }
}

I know there no documents with usernames a, b and c but deleteMany() doesn't return any error something like "Coulnd't find given parameter" etc.

because I don't want to response with "User(s) successfully deleted". How can I catch that error if there is one. Or How should I handle that?

Upvotes: 2

Views: 2739

Answers (3)

turivishal
turivishal

Reputation: 36134

You may change your functions to below,

@ user.controller.js:

  • put async/await in function, and add code in try/catch block, and pass res as param in service function deleteByUsernames,
async function _deleteByUsernames(req, res, next) {
    try {
        await userService.deleteByUsernames(res, JSON.parse(req.query.usernames));
    } catch (err) {
        next(err);
    }
}

@ user.service.js:

deleteMany(), This function calls the MongoDB driver's Collection#deleteMany() function. The returned promise resolves to an object that contains 3 properties:

ok: 1 if no errors occurred

deletedCount: the number of documents deleted

n: the number of documents deleted. Equal to deletedCount.

async function _deleteByUsernames(res, usernames) {
    let response = await User.deleteMany({ username: { $in: usernames } });
    // ERROR
    if (response.ok != 1) {
        res.status(400).json({ "message": "User(s) not deleted, Something want wrong!" });
    }
    // SUCCESS 
    else {
        res.status(200).json({ 
          "message": `${response.deletedCount} User(s) successfully deleted out of ${response.n}"
        });
    }
}

Code is not tested, you can workaround and see what happens!

Upvotes: 2

ahmetkca
ahmetkca

Reputation: 637

I think there is no error for no found parameters. I don't know this is better than nothing for now. I am not going to mark this as answered because I don't think this is the answer

async function _deleteByUsernames(usernames) {
    return await User.deleteMany({username: {$in: usernames}})
        .then(result => {
            console.log(result);
            return (result.deletedCount === 0 ? 
                "None of the selected user(s) deleted!": 
                (result.deletedCount !== usernames.length ? 
                `${result.deletedCount} out of ${usernames.length} selected user(s) successfully deleted!`: 
                "All selected user(s) successfully deleted!"))
        })
        .catch(err => {
            return `Delete failed with error: ${err}`;
        })
}

Upvotes: 2

Fahad Subzwari
Fahad Subzwari

Reputation: 2335

You can save your delete result in a variable and check for the error

async function _deleteByUsernames(usernames) {
try {
    console.log(usernames);
    let userDeleteResult = await User.deleteMany({username: {$in: usernames}});
    if(!userDeleteResult ){
      res.json({status: false, error: 'Some error'}) // or pass the error object here
    }
   } catch (err) {
    throw err;
  }
 }

Upvotes: -1

Related Questions