Saturday, 18 April 2020

Mongoose: how to update a document when a subdocument is updated?

Hi,I have a User document which contains a messages array. This messages array is populated by Conversations documents whose User is part of. const userSchema = new mongoose.Schema({ // classic infos (password, email, etc.) messages: [{ type: Schema.types.ObjectId, ref: "Conversation" }] } const conversationSchema = new mongoose.Schema( { name: { type: String, required: true, unique: true }, senderId: { type: Schema.Types.ObjectId, ref: "User" }, recipientId: { type: Schema.Types.ObjectId, ref: "User" }, messageList: [{ message: { type: String }, author: { type: String } }], latestMessage: { author: { type: String }, msgSnippet: { type: String }, read: { type: Boolean }, }, default: null, }, { timestamps: true } ); conversationSchema.index({ name: 1 }); When someone writes a message in a Conversation, the field latestMessage is updated. This way, the client can know there are unread messages if latestMessage's author is different from the client user, and read is false. read will be updated to true when the recipient opens the conversation.For the moment, this technique requires to fetch all conversation's latestMessage on every page refresh to do a long checking. Is it possible to automatically update User with a field hasUnreadMessage after each new post insertion?Attention, hasUnreadMessage should not switch to false just because of a single conversation logic. Indeed, what if other conversations have unread messages for him? It seems middleware "pre" can do marvels, but I'm no master at it so far.Thanks!

Submitted April 18, 2020 at 08:32PM by MonsieurLeland

No comments:

Post a Comment