MongoDB字符串切片存储问题:无法向likes数组添加userID
问题:向MongoDB的null类型likes字段添加userID失败
问题详情
尝试向MongoDB的likes字段添加userID,该字段预期为字符串数组[]string,但当前值为null。先后使用$set操作、手动将字段设为数组后改用$setOnInsert、$addToSet,均未成功触发写入。
创建文档时使用的结构体:
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}
向"likes":null字段添加userID时,在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{} // 检查用户是否已点踩 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 { // 移除点踩 update = append(update, bson.E{Key: "$pull", Value: bson.D{{Key: "dislikes", Value: userID}}}) } // 检查用户是否已点赞 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 { // 移除点赞 update = append(update, bson.E{Key: "$pull", Value: bson.D{{Key: "likes", Value: userID}}}) } else { // 添加点赞 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()}}}) // 写入失败位置 _, 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)
内容的提问来源于stack exchange,提问作者Mike3355
相关产品推荐
相关产品推荐

