使用Complex SimpleSchema更新Chat App中的读取状态

时间:2018-05-09 08:19:14

标签: mongodb meteor mongodb-query simple-schema simpl-schema

下面是使用 Meteor 1.6 MongoDB 3.4

Chats集合中存储文档的简单JSON格式
{ 
    "_id" : "PN27eK2DWoRXmFrzB", 
    "members" : [
        "BtKnXevDi3hm8CmMP", 
        "whLGMxdPwFkR6sNoy"
    ], 
    "details" : [
        {
            "message" : "cool", 
            "sender" : "BtKnXevDi3hm8CmMP", 
            "read" : false, 
        }, 
        {
            "message" : "you there buddy?", 
            "sender" : "whLGMxdPwFkR6sNoy", 
            "read" : false, 
        }
    ]
}

简单架构如下所示;

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 });

到目前为止,我已经构建了以下查询来更新嵌套数据details.$.read

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

预期输出是details sender "BtKnXevDi3hm8CmMP" read必须将true字段设置为"details" : [ { "message" : "cool", "sender" : "BtKnXevDi3hm8CmMP", "read" : true, }, { "message" : "you there buddy?", "sender" : "whLGMxdPwFkR6sNoy", "read" : false, }, ] ,如下所示;

db.getCollection('yourTable').aggregate([
{
   $project :
       {
           "id" : 1,
           "name" : 1,
           "online": 1,
           "like" : 1,
           "score" : 1,
           onlineSortLike: {
            $cond: {
              if: { $and: [{ $eq: ['$online',1 ] }] },
              then: '$like', 
              else: 0,
            },
          },
          sortOfflineScore: {
            $cond: {
              if: { $and: [{ $eq: ['$online',0] }] },
              then: '$score', 
              else: 0,
            },
          },
          sortOfflineScoreLike: {
            $cond: {
              if: { $and: [{ $eq: ['$online', 0] }] },
              then: '$like', 
              else: 0,
            },
          },


       }
},
{
   $sort :
       {
           "online" : -1,
           "onlineSortLike" : -1,
           "sortOfflineScore" : -1,
           "sortOfflineScoreLike" : -1
       }
},
{
   $skip : 0
},
{
   $limit : 9
}
])

需要帮助来纠正我的疑问并了解我哪里出错?

0 个答案:

没有答案