我正在尝试更新mongodb文档中放置的数组中的元素。通常,在更新操作之后,我会得到整个文档,但我希望返回最新更新的元素:
{
_id: new ObjectId("6471fe4a0045e48a0c6193ba"),
gateways: [
{
_id: '5231db1f-b79a-4dc3-a387-6f08ad7b6857',
name: 'Babylon Dev',
right: 'owner'
}
],
__v: 0,
notifications: [
{
type: 'confirm',
title: 'Gateway whitelist request!',
description: '6471fe4a0045e48a0c6193ba wants to share data from gateway 5231db1f-b79a-4dc3-a387-6f08ad7b6857 with you.',
actions: [Array],
from: '6471fe4a0045e48a0c6193ba',
subject: '5231db1f-b79a-4dc3-a387-6f08ad7b6857',
status: 'unread',
_id: new ObjectId("64b6791adbf7bb6eaa528cf2")
},
{
type: 'confirm',
title: 'Gateway whitelist request!',
description: '6471fe4a0045e48a0c6193ba wants to share data from gateway 5231db1f-b79a-4dc3-a387-6f08ad7b6857 with you.',
actions: [Array],
from: '6471fe4a0045e48a0c6193ba',
subject: '5231db1f-b79a-4dc3-a387-6f08ad7b6857',
status: 'unread',
_id: new ObjectId("64b6791adbf7bb6eaa528cf5")
}
]
}
字符串
我想将通知status
属性从unread
更新为read
或confirmed
,并返回更新后的通知。有没有一种简单的方法可以在一个查询中完成此操作?查询将根据文档的_id
和通知的_id
进行更新。用户模式:
@Schema()
export class User {
@Prop( { type: [ GatewaySchema ], default: [] } )
@IsArray( { each: true } )
@Type( () => Gateway )
@Expose()
gateways?: Array<Gateway>;
@Prop( { type: [ NotificationSchema ], default: [] } )
@IsArray( { each: true } )
@Type( () => Notification )
@Expose()
notifications?: Array<Notification>;
}
型
通知架构:
@Schema()
export class Notification {
@IsMongoId()
@Expose()
@Prop( { type: Types.ObjectId } )
_id: Types.ObjectId;
@IsString()
@Expose()
@Prop( { type: String, enum: NotificationLevels, default: NotificationLevels.info } )
type?: NotificationLevels;
@IsString()
@Expose()
@Prop( { type: String, required: true } )
title: string;
@IsString()
@Expose()
@Prop( { type: String, required: true } )
description: string;
@IsString()
@Expose()
@Prop( { type: Array, enum: NotificationAction, default: [ NotificationAction.mark ], required: false } )
actions?: Array<NotificationAction>;
@IsMongoId()
@Prop( { type: Types.ObjectId, required: true } )
for: Types.ObjectId;;
@IsMongoId()
@Prop( { type: Types.ObjectId, required: true } )
from: Types.ObjectId;
@IsUUID()
@Prop( { type: String, required: true } )
subject: string;
@IsString()
@Expose()
@Prop( { type: String, enum: NotificationStatus, default: NotificationStatus.unread } )
status: NotificationStatus;
}
型
进度:
为了更新通知,我使用此方法:
db.collection.findOneAndUpdate( { _id: userId, 'notifications._id': notificationId }, { $set: { 'notifications.$.status': 'confirmed' } }, { arrayFilters: [ { _id: notificationId } ], projection: { 'notifications.$': 1 }, new: true } );
型
这很好,但我希望返回的对象是刚刚更新的通知。有点像聚合查询。有什么想法吗
1条答案
按热度按时间bq3bfh9z1#
你可以试着做这样的事情。您可以将要更新的字段名称传递给find one and update方法中的projection选项。
举例来说:
字符串
也许这将帮助您获得所需的输出。