Home > Mobile >  How to delete items by _id using mongodb
How to delete items by _id using mongodb

Time:11-29

I have a problem trying to delete data by providing an array of id's (got error). I guess it has something to do with ObjectId. Could you help me fix it?

User.deleteMany({
  _id: { $in:     ['638207a8b9ebc3ea8f276684',
                  '63823ffe310abc61b4ee11a0',
                  '63822a71319517d196af6d59' }
})
.then(() => res.status(200).json({ success }))
.catch(error => console.error('Error deleting users'))

I tried to map this array to prepend every item of it with ObjectId but got ObjectId is not found.

CodePudding user response:

Try this..

let userIds = ['638207a8b9ebc3ea8f276684',
    '63823ffe310abc61b4ee11a0',
    '63822a71319517d196af6d59']
    let userObjectIds = userIds.map(e=>Types.ObjectId(e))
    User.deleteMany({
        _id: { $in:  userObjectIds  }
      })
      .then(() => res.status(200).json({ success }))
      .catch(error => console.error('Error deleting users'))

CodePudding user response:

If the code you pasted above is the exact code you are running, the problem is likely your input ids array syntax. It seems as though you are missing a close square bracket (]). Try this instead:

const userIds = ['638207a8b9ebc3ea8f276684', '63823ffe310abc61b4ee11a0', '63822a71319517d196af6d59']
User.deleteMany({
  _id: { $in: userIds }
})
.then(() => res.status(200).json({ success }))
.catch(error => console.error(`Error deleting users: ${error}`))

If that doesn't work, you may need to follow Alex's advice by mapping them to ObjectId types. As a side note, it's always good practice to save your input into a variable rather than hard code it. It's also helpful for debugging to log the contents of the error from your catch callback

console.error(`this is my error: ${error}`)

Hope that helps you out, happy coding :)

  • Related