Home > front end >  Delete an already retrieved element with mongoose
Delete an already retrieved element with mongoose

Time:06-24

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 ?

CodePudding user response:

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();
  • Related