我有一个聊天结构,可将所有消息和最后一条消息都保存在一个父文档(chat
)中。当用户发送消息时,我需要更新last_message
并将新消息附加到messages
数组中。是否可以在一个单一的更新不透明状态下进行操作,以便两个子文档中的_id
,created_at
和updated_at
都相同?
这是我的无效尝试:
const message = {
content: req.body.contentg,
sender: sender.toObject(),
};
const chat = await Chat.findOneAndUpdate({
_id: toObjectId(req.params.chat_id),
status: 'active',
}, {
last_message: message,
$push: { messages: message },
}, {
new: true,
});
更新:添加了架构(我使用的是ts-mongoose)
export const MessageSenderSchema = createSchema({
last_name: Type.string(),
first_name: Type.string(),
phone: Type.string({ required: true }),
email: Type.string(),
status: Type.string({ enum: UserStatuses, required: true }),
}, {
skipVersioning: true,
});
export const ChatMessageSchema = createSchema({
content: Type.string({ required: true }),
status: Type.string({ enum: ChatMessageStatuses, default: 'new' }),
sender: Type.schema({ require: true }).of(MessageSenderSchema),
});
ChatMessageSchema.set('timestamps', { createdAt: 'created_at', updatedAt: 'updated_at' });
export const ChatSchema = createSchema({
__v: Type.number({ select: false }),
status: Type.string({ enum: ChatStatuses, default: 'active', required: true }),
members: Type.array().of({
$ref: Type.string(),
$id: Type.objectId(),
$db: Type.string({ required: false }),
}),
messages: Type.array().of(ChatMessageSchema),
last_message: Type.schema().of(ChatMessageSchema),
});