Để cập nhật một đối tượng bên trong một mảng lồng nhau trong MongoDB, bạn có thể sử dụng phương pháp này, Nó đã được thử nghiệm và hoạt động tốt Trường hợpCập nhật các đối tượng mảng lồng nhau. Xem hình dưới đây để biết rõ hơn về những gì chúng ta sẽ làm. Chúng tôi sẽ cập nhật đối tượng được lồng bởi 3 cấp độ của mảng
{
discussionList[
discussionList [
{
object-value-to-be-updated.
}
]
]
}
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình Giải pháppublic courseCategoryPostCommentReplyUpdate(operation: CommentReplyUpdateMutation): Promise<IDocumentUpdateType> {
return this.courseCategoryPostCommentsModel.updateOne(
{
"postId" : operation.postId,
'discussionList': {
'$elemMatch': {
'_id': operation.commentId,
"discussionList._id": operation.replyId
}
}
},
{
$set: {
"discussionList.$[outer].discussionList.$[inner].payload": operation.payload,
"discussionList.$[outer].discussionList.$[inner].isUpdated": true,
"discussionList.$[outer].discussionList.$[inner].commentUpdateTime": new Date()
}
},
{
arrayFilters: [
{ "outer._id": operation.commentId},
{"inner._id": operation.replyId}
]
}
);
}
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình FootNotes - mã này là để cập nhật câu trả lời của một bình luận Đó là cách bạn có thể thực hiện các thao tác trên một đối tượng trong mảng lồng nhau trong tài liệu mongoDB. Bạn cũng có thể cập nhật/xóa các đối tượng có mức độ lồng ghép cao hơn bằng cách sửa đổi truy vấn Ví dụ về xóa và nhậnXóa bỏ// Informational Note:
// Delete nested array values in mongodb
public courseCategoryPostCommentReplyDelete(operation: CommentReplyDeleteMutation): Promise<IDocumentUpdateType> {
return this.courseCategoryPostCommentsModel.updateOne(
{
'postId': operation.postId,
'discussionList': {
'$elemMatch': {
'_id': operation.commentId,
'discussionList._id': operation.replyId
}
}
}, {
$pull: {
'discussionList.$[outer].discussionList': {
user: operation.userId,
_id: operation.replyId
}
}
},
{
arrayFilters: [
{ 'outer._id': operation.commentId }
],
multi: false
}
);
}
}
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình ĐƯỢCpublic courseCategoryPostCommentRead(postId: string): Promise<IComment> {
return this.courseCategoryPostCommentsModel.findOne<IComment>({
postId: postId
}).populate('discussionList.user').populate('discussionList.discussionList.user').exec();
}
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình Tôi đang sử dụng GraphQL. Bạn có thể cần lặp lại kết quả và hiển thị nhận xét/câu trả lời theo đó |