Update my read status in Chat App with Complex SimpleSchema

31 Views Asked by At

Below is the simple JSON format for a stored document in my Chats collection using Meteor 1.6 and MongoDB 3.4

{ 
    "_id" : "PN27eK2DWoRXmFrzB", 
    "members" : [
        "BtKnXevDi3hm8CmMP", 
        "whLGMxdPwFkR6sNoy"
    ], 
    "details" : [
        {
            "message" : "cool", 
            "sender" : "BtKnXevDi3hm8CmMP", 
            "read" : false, 
        }, 
        {
            "message" : "you there buddy?", 
            "sender" : "whLGMxdPwFkR6sNoy", 
            "read" : false, 
        }
    ]
}

Simple Schema looks like below;

ChatsSchema = new SimpleSchema({
    'members': { type: Array, optional: true, minCount: 2, maxCount: 2 },
    'members.$': String,
    'details': { type: Array, optional: true },
    'details.$': Object,
    'details.$.sender': { 
        type: String, 
        optional: true,
        autoValue: function(){
            return Meteor.userId();
        }
    },
    'details.$.message': { type: String, min: 1, max: 200 },
    'details.$.read': { type: Boolean, defaultValue: false },
    'details.$.createdAt': {
        type: Date,
        autoValue: function(){ return new Date(); }
    },
},{ tracker: Tracker });

I have below query built so far to update nested data details.$.read.

let members = [ "BtKnXevDi3hm8CmMP", "whLGMxdPwFkR6sNoy"];
let otherUserId = 'BtKnXevDi3hm8CmMP'
Chats.update({
        members: {$in: members},
        'details' : { "$elemMatch": { "sender": otherUserId } }
    }, 
    { 
        $set: { 
            'details.$.read': true
        } 
    });

Expected output is such that details with sender as "BtKnXevDi3hm8CmMP" must have read field set to true, as below;

"details" : [
        {
            "message" : "cool", 
            "sender" : "BtKnXevDi3hm8CmMP", 
            "read" : true, 
        }, 
        {
            "message" : "you there buddy?", 
            "sender" : "whLGMxdPwFkR6sNoy", 
            "read" : false, 
        }, 
    ]

Need help to rectify my query and understand where I am going wrong?

0

There are 0 best solutions below