[英]mongodb/mongoose findOneandUpdate how to get index and delete object
所以我有事件對象,它具有注釋,並且注釋具有likes數組。 我目前能做的是向事件對象的comments數組添加類似內容。
我的架構看起來與此類似:
creator: {
type: Schema.Types.ObjectId,
ref: 'User'
},
comments: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
text: {
type: String,
required: true
},
likes: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'User'
}
}
]
}
]
}
我當前的“添加到評論”功能看起來像這樣:
commentLike: async (req, res) => {
console.log('working', req.params.id, req.params.idas, req.params.commentID);
Events.findOneAndUpdate(
{ _id: req.params.idas, comments: { $elemMatch: { _id: req.params.commentID } } },
{ $push: { 'comments.$.likes': { user: req.params.id } } },
(result) => {
res.json(result);
}
);
}
參數:idas- event._id,commentID:評論ID,ID:user._id
問題是我可以添加無盡的贊,因為我沒有邏輯操作來檢查用戶是否已經喜歡它,並且我真的很掙扎,在此findoneandupdate函數中無法做到這一點。 但這就是問題,我想做的另一件事是與評論不同,而林先生對於如何從Likes數組中獲取用戶索引以便於可以將其切出的內容搞不清,目前我的功能如下所示:
deleteLike: async (req, res) => {
console.log('working', req.params.id, req.params.idas, req.params.commentID);
Events.findOneAndUpdate(
{ _id: req.params.idas, comments: { $elemMatch: { _id: req.params.commentID } } },
{
$push: {
'comments.$.likes': {
$each: [],
$slice: 0 //there instead of 0 should be user index
}
}
},
(result) => {
res.json(result);
}
);
}
在此函數上,我還使用findoneandupdate函數,這可能不是一個好主意嗎? 試圖使用findandremove,但是它刪除了整個事件對象。
所以我設法通過使用拉運算符。 工作刪除評論,如功能
deleteLike: async (req, res) => {
console.log('working', req.params.id, req.params.idas, req.params.commentID);
Events.findOneAndUpdate(
{ _id: req.params.idas, comments: { $elemMatch: { _id: req.params.commentID } } },
{
$pull: { 'comments.$.likes': { user: req.params.id } }
},
(result) => {
res.json(result);
}
);
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.