用猫鼬删除数组中的子文档

remove subdocument in array with mongoose

您好,我的数据库中有一个这样的条目:database entry,我想从心愿单中删除一个子文档,例如:222223。我尝试使用以下代码这样做:

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);
}

当我尝试发出删除请求时,我的 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
}

它好像没有从心愿单数组中找到条目“222223”?

什么都没发生的原因是你没有告诉 mongoose 执行你的请求。

当调用findOne()updateOne()deleteMany()或任何其他与你的猫鼬模型相关的方法时,你得到的只是一个Query。如果你想让它被执行,你需要使用 awaitexec() 方法。

这就是您在调用模型的 findOne(...) 方法时所做的。你只是忘了在 product.updateOne(...) 之前加上一个 await