Home > Software engineering >  remove subdocument in array with mongoose
remove subdocument in array with mongoose

Time:03-15

Hi I have an entry like this in my database: database entry and want to remove a subdocument from the wishlist, ex: 222223. I have tried doing so with the following code:

async removeProduct(visitorID: number, productID: number) {
    const product = await this.visitorModel.findOne({ visitorID: visitorID });
    console.log(product);
    
    product.updateOne({
        $pull: {
            wishlist: productID
        }
    }, { new: true })
    

    console.log(product);
}

When I try to make an delete request I get the following result printed with my console.logs:

{
  _id: new ObjectId("6228c61d0f4a800664f46eb5"),
  visitorID: 2122323,
  wishlist: [ 222223, 22222, 22222 ],
  __v: 2
}
{
  _id: new ObjectId("6228c61d0f4a800664f46eb5"),
  visitorID: 2122323,
  wishlist: [ 222223, 22222, 22222 ],
  __v: 2
}

its like it doesn't find the entry "222223" from the wishlist array?

CodePudding user response:

The reason why nothing is happening is because you are not telling mongoose to execute your request.

When calling findOne(), updateOne(), deleteMany() or any other method related to your mongoose model, what you get is only a Query. If you want it to be executed you need to use await or the exec() method.

And that's what you did when you called your model's findOne(...) method. You just forgot to put an await before product.updateOne(...).

  • Related