Error: {"message":"'remove' is not a function","name":"TypeError"}

Hello, Query we are firing from Atalas Trigger.
Atlas version: 4.4.18

Trigger:

exports =async  function() {
	let collections = context.services.get("XYZZZ").db("XXXXX");
	let orderhistoryCollection = collections.collection("XXXXXX");
	const pipeline  =[
	{
      $match: {
           creationDate: {
                          $ne: "",
                         }
            }
  },
  {
    $addFields: {
     created_at: {
        $toDate: "$creationDate",
      },
    },
  },
  {
    $match:{
  "created_at":{$lt:new Date(getThreshholdDate())}
},
  },
  {
    $project: {
      _id: "$_id"

    },
  },
];
const idList = await  orderhistoryCollection.aggregate(pipeline).toArray();

console.log("No of documents deleted: "+idList.length);
//console.log(idList);
if(idList.length>0){
orderhistoryCollection.remove({ _id: { $in: idList } });
}
return idList;
  
}

function getThreshholdDate() {
 let date = new Date();
 date.setMonth( date.getMonth() - 7 );
 console.log(date.getFullYear()+"-"+date.getMonth()+"-"+date.getDate());
 return date;
}

Error:

{“message”:"‘remove’ is not a function",“name”:“TypeError”}

Logs:

[ “2022-11-6”, “26200” ]

1 Like

Perhaps you want deleteMany rather than remove?

2 Likes

Changed the code to deleteMany but it is not deleting records. Am I missing something?

console.log("No of documents to be deleted: "+idList.length);
if(idList.length>0){
  const deleteResult = await orderhistoryCollection.deleteMany({ _id: { $in: idList } });
  console.log("Deleted " + deleteResult.deletedCount + " documents");
}

ran on Fri Jan 06 2023 12:56:03 GMT-0600 (Central Standard Time)
took 4.528895883s
logs:
2022-5-6
No of documents to be deleted: 50000
Deleted 0 documents

What is the output of:

console.log(orderhistoryCollection.find({ _id: { $in: idList } }).count());

N.B.: Depending on how/where you call this, you may need await, etc.

Fixed issue with this code change

const idList = await  orderhistoryCollection.aggregate(pipeline).toArray();
console.log("No of documents to be deleted: "+idList.length);

if(idList.length>0){
  try{
    let ids=[];
    idList.forEach(doc=>ids.push(doc._id));
    const deleteResult = await orderhistoryCollection.deleteMany({ _id: { $in: ids } });
    console.log("Deleted " + deleteResult.deletedCount + " documents");
  }
  catch(e)
  {
    console.log(e);
  }
}
2 Likes

Please Use deleteOne() Instead remove() function. If you want to delete single item deleteOne( ) & if there ary many documents there please use other delete Options.

5 Likes

remove() function is deprecated, now you may use deleteOne() or deleteMany() functions instead of that.

2 Likes