Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: remove() returns true for already deleted items

my code below returns "User deleted" even if the user was already deleted. I'd prefer to throw a 404 in this case, but I'd like to query the DB as less as possible.

Is there a way to get the userNotFound (see below) without manually checking if the user existed before deletion? Maybe I missed a feature of remove() or an alternative function.

var itemId = 123;
Item.remove({id: itemId}, function(err) {
    if (err) {
        return res.json({success: false, msg: 'Cannot remove item'});
    }

    // !!!
    if (userNotFound) {
        return res.status(404).json({success: false, msg: 'User not found'});
    }  
    // /!!!


    res.json({success: true, msg: 'User deleted.'});
});

Thanks in advance!

like image 719
Mr. B. Avatar asked Feb 21 '17 08:02

Mr. B.


People also ask

How do you delete an item from MongoDB using Mongoose?

There is currently no method called deleteById() in mongoose. However, there is the deleteOne() method with takes a parameter, filter , which indicates which document to delete. Simply pass the _id as the filter and the document will be deleted.

What is the Mongoose command used to delete an item?

Mongoose | deleteOne() Function The deleteOne() function is used to delete the first document that matches the conditions from the collection. It behaves like the remove() function but deletes at most one document regardless of the single option.

How do you clear a Mongoose?

We can delete documents using mongoose with the help of different methods like Model. deleteOne(), Model. findOneAndDelete(), Model. deleteMany(), and Model.

What does Mongoose model return?

The mongoose. model() function of the mongoose module is used to create a collection of a particular database of MongoDB. The name of the collection created by the model function is always in plural format mean GFG to gfss and the created collection imposed a definite structure.


1 Answers

The problem with the above approach is that userNotFound will always be undefined since you haven't defined it in the callback arguments. Better to use the findOneAndRemove() function so that you can return the document removed if found:

var itemId = 123;
Item.findOneAndRemove({ id: itemId }) 
    .exec(function(err, item) {
        if (err) {
            return res.json({success: false, msg: 'Cannot remove item'});
        }       
        if (!item) {
            return res.status(404).json({success: false, msg: 'User not found'});
        }  
        res.json({success: true, msg: 'User deleted.'});
    });
like image 142
chridam Avatar answered Nov 14 '22 22:11

chridam