Search code examples
mongoosemongoose-schema

Delete an already retrieved element with mongoose


I already know about findByIdAndRemove(), but I want to know if there is a function to delete something Ive already retrieved from the database like .save(), heres an example:

// Account is our model
const foundAccount = await Account.findById(userId);
// Do something with found account
await foundAccount.[the function to delete this object]();

Or if the only way is with findByIdAndRemove():

// Account is our model
const foundAccount = await Account.findById(userId);
// Do something with found account
await Account.findByIdAndRemove(foundAccount._id);

And last, if there is such a function, does it make any difference in regards to performance with using findByIdAndRemove() separately ?


Solution

  • You can use deleteOne() or remove():

    // Account is our model
    const foundAccount = await Account.findById(userId);
    // Do something with found account
    await foundAccount.deleteOne();
    // or
    // await foundAccount.remove();