1

I try to remove more than one document with mongoose.

I've try something like this.

const result = await Order.remove({id: {$in: req.body.id}});

But, it doesn't work!

The output of req.body.id is array.

To make sure that req.body.id is an array. I try something like this:

req.body.id.constructor === Array

and the output is true

What is wrong?

UPDATE

Here is my req.body.id : [ '5ab0a359672f32ad94c5aa2d', '5ab0a3d25e7bef513cd882ff' ]

Abid Rakhmansyah
  • 896
  • 8
  • 22

2 Answers2

3

For this you first need to convert them into MongoDB objectID. Try this

const result = await Order.remove({id: {$in: (req.body.id).map(mongoose.Types.ObjectId)}});
Muhammad Usman
  • 10,039
  • 22
  • 39
1

You have to convert your array element into ObjectId then you can delete multiple documents at a time.

Like,

Model.remove({_id: {$in: [ObjectId('5a9552ab72fa59ef5ac697f0'), ObjectId('5a9553c072fa59ef5ac6986e')]}});

If its match and removed then you will get a response like this { "nRemoved" : 2 }

If you are using mongoose, then you can do like this,

const mongoose = require('mongoose')
const ObjectId = mongoose.Types.ObjectId

and then you can convert it like ObjectId('YOUR_ID')

Naimish Kher
  • 284
  • 1
  • 9