我正在尝试将 userID 添加到 MongoDB 中的 likes 字段。此字段将是一个字符串数组[]string
。它当前为空,但这不应该是问题,因为使用的是"$set"
。我还尝试手动将字段设为数组并使用$setOnInsert
和$addToSet
代替,但$set
无济于事。
我正在使用这个结构创建文档:
comment := entity.Comment{
PostID: postID,
Content: content,
AuthorID: authorID,
Likes: []string{},
Dislikes: []string{},
Votes: []string{},
CreatedAt: time.Now(),
}
相关文档在数据库中如下所示:
{"_id":{"$oid":"67de0487653132119ba14548"},"postid":"67de00a0eea2fe8f5a55e1da","content":"awesome Pizza day","authorid":"3204aa18-2006-4aa1-ad88-1b71256d8a36","createdat":{"$date":{"$numberLong":"1742603399198"}},"updatedat":{"$date":{"$numberLong":"1742603992797"}},"likes":null,"dislikes":null,"votes":null}
现在,我正在尝试向中添加一个用户 ID 字符串"likes":null,"dislikes":null
。
它在 UpdateOne 处因写入异常而失败。userID
和comment.ObjectId
不为空,并且comment.ObjectId
确实存在于数据库中。目前只有一条评论。
func (r *CommentsRepository) ToggleLikeComment(ctx context.Context, comment *entity.Comment, userID string) error {
filter := bson.D{{Key: "_id", Value: comment.ObjectId}}
update := bson.D{}
// Check if user already disliked
dislikeFilter := bson.D{{Key: "_id", Value: comment.ObjectId}, {Key: "dislikes", Value: userID}}
dislikeCount, err := r.collection.CountDocuments(ctx, dislikeFilter)
if err != nil {
return err
}
if dislikeCount > 0 {
// Remove dislike
update = append(update, bson.E{Key: "$pull", Value: bson.D{{Key: "dislikes", Value: userID}}})
}
// Check if user already liked
likeFilter := bson.D{{Key: "_id", Value: comment.ObjectId}, {Key: "likes", Value: userID}}
likeCount, err := r.collection.CountDocuments(ctx, likeFilter)
if err != nil {
return err
}
if likeCount > 0 {
// Remove like
update = append(update, bson.E{Key: "$pull", Value: bson.D{{Key: "likes", Value: userID}}})
} else {
// Add like
update = append(update, bson.E{Key: "$set", Value: bson.D{{Key: "likes", Value: userID}}})
}
update = append(update, bson.E{Key: "$set", Value: bson.D{{Key: "updatedat", Value: time.Now()}}})
// fails to write here...
_, err = r.collection.UpdateOne(ctx, filter, bson.D{{Key: "$set", Value: update}})
return err
}
在@aneroid 的帮助下,我能够调整代码。以下是最终有效的查询
likeFilter := bson.D{
{Key: "_id", Value: objectID},
{Key: "likes", Value: bson.D{{Key: "$ne", Value: userID}}},
}
likeUpdate := bson.A{
bson.D{{Key: "$set", Value: bson.D{
{Key: "likes", Value: bson.D{
{Key: "$cond", Value: bson.D{
{Key: "if", Value: bson.D{{Key: "$eq", Value: bson.A{"$likes", nil}}}},
{Key: "then", Value: bson.A{userID}},
{Key: "else", Value: bson.D{{Key: "$concatArrays", Value: bson.A{"$likes", bson.A{userID}}}}},
}},
}},
{Key: "updatedat", Value: time.Now()},
}}},
}
result, err := r.collection.UpdateOne(ctx, likeFilter, likeUpdate)