Home > Enterprise >  How to perform mongoose deleteMany() with query operators?
How to perform mongoose deleteMany() with query operators?

Time:06-20

I want to delete X number of posts starting from the most recently created for a specific user.

How can I apply this logic using mongoose so that I can perform just ONE database operation instead of first having to query for these posts and remove them one by one?

I am finding using the query and projection operators with the $ very confusing, any help would be appreciated.

Below I added pseudo code on how it should to work.

Thank you!

const userId = "123456"
const deleteCount = 6

const deletedPosts = await Post.deleteMany({
      .where { userid == userId) }
      .sort({createdAt: -1}) // delete by most recent
      .limit(deleteCount)    // only delete 6 (most recent) posts
      }, {new: true})        // return results of operation

console.log(deletedPosts.deletedCount) // -> should be "6"

CodePudding user response:

You can't set a limit when using deleteMany or findAndModify. So, if you want to precisely limit the number of documents removed, you'll need to do it in two steps.

  1. db.getCollection('users').find({}, {class : 4}) .limit(2) .sort({StudentAge: -1}) .toArray() .map(function(doc) { return doc._id; }); //returns the array of id's

  2. db.getCollection('users').deleteMany({_id: {$in: [ "s3", "s4" ]}})//put the array of id's

Data in model

1st query

2nd query

Final output

  • Related