[英]MongoDB/Mongoose $pull an Object in an Array where _id of the Object is matching
我在這里有這個架構
考慮likedTours
,它是一個對象數組(旅游)(忽略 position 0)。 我想提取 Tour 的_id
與標准匹配的任何對象。
喜歡旅游時添加新的旅游是可以的,但不像我不知道如何把那個項目拉出來。
這是我在 Node.JS 后端的 Controller 中的 function
const unlikeTour = async (req, res) => {
try {
TourDB.Tour.findOneAndUpdate(
{ _id: req.params.tourid },
{
$pull: { likedUsers: req.userID },
$inc: { likes: -1 },
}
).exec(async (err, docs) => {
if (!err) {
try {
await UserDB.User.findOneAndUpdate(
{ _id: req.userID },
{ $pull: { 'likedTours._id': docs._id } } //Here I need help
).exec()
return res.status(200).send({ successMessage: 'Tour successfully unliked' })
} catch (err) {
return res.status(500).send({ errorMessage: 'User not found' })
}
} else {
return res.status(500).send({ errorMessage: 'Tour not found' })
}
})
} catch (err) {
return res.status(500).send({ errorMessage: err })
}
}
此方法查找游覽並通過提取用戶 ID 並將喜歡計數減少 -1 來更新它。 然后我嘗試在用戶數據庫中找到likedTours
中的巡演並嘗試拉,但它不能那樣工作。
提前致謝
你可以更新為
await UserDB.User.findOneAndUpdate(
{ _id: req.userID },
{ $pull: { likedTours: { _id: docs._id } } } //Here I need help
).exec();
參考:https://docs.mongodb.com/manual/reference/operator/update/pull/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.