0

I'm not sure why the removal doesn't work using the latter method. (foundList is not null)

Latter method:

    List.findOne({name: listType}, function(err, foundList){
      if (err){
        console.log(err);
      } else {
        foundList.updateOne({}, { $pull: { item: { _id: itemID } } });
        console.log('deletion success');
        res.redirect("/" + listType);
      }
    });
  }

Schema:

const itemSchema = {text: String}
const listSchema = {  
  name: String,
  item: [itemSchema]
}
zhulien
  • 5,145
  • 3
  • 22
  • 36
  • You get different result for `findOneAndUpdate` and `updateOne` is because `findOneAndUpdate` will return old document if option `{ new: true}` is not passed as third argument to the API. – Dheemanth Bhat Apr 04 '21 at 20:16

1 Answers1

1

Below line is wrong and wont work. This is because foundList contains result of the query findOne.

foundList.updateOne({}, { $pull: { item: { _id: itemID } } });

After you call List.findOne({name: listType}, function(err, foundList), foundList contains result of the query, and you cannot call any query/mongoose-api on that. You need to call mongoose APIs like updateOne on the model object, only then you will get the result.

What you can do is you can modify that document and then save it. You can do that like this:

List.findOne({name: listType}, function(err, foundList){
      if (err){
        console.log(err);
      } else {
        let index = foundList.findIndex((list: any) => list.item._id == itemID );
        if (index !== -1) {
            foundList.splice(index, 1);
        }
        foundList.save().then(()=>{
            console.log('deletion success');
            res.redirect("/" + listType);
        })
     }
})

Or you can do all that in one query. Try this:

List.findOneAndUpdate({name: listType}, {
   $pull: {
       item: { _id: itemID } 
   }, {new:true})
.then((response) => {
   console.log('deletion success');
   res.redirect("/" + listType);
})
.catch((err) => res.json(err));

NOTE: Also make sure itemID is of type ObjectId and not string. You can typecast string to ObjectId as shown here.

Dheemanth Bhat
  • 4,269
  • 2
  • 21
  • 40
NeNaD
  • 18,172
  • 8
  • 47
  • 89