Franchesco Livado
Franchesco Livado

Reputation: 21

MongoDB Different result using .findOneAndUpdate() vs .updateOne nested in findOne

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]
}

Upvotes: 0

Views: 292

Answers (1)

NeNaD
NeNaD

Reputation: 20354

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.

Upvotes: 1

Related Questions