另一天。另一个 Mongodb 查询。
我希望在我的一个集合中创建以下结构:
amitverma是用户,嵌套对象是消息的 UTC 时间戳。我想按以下结构推送消息。
{
    "username" : "macbook",
    "messages" : {
        "amitverma" : {
            "1383321755" : {
                "to" : "macbook",
                "message" : "hi.",
                "sender" : "amitverma",
            },
            "1383321712" : {
                "to" : "macbook",
                "message" : "hi.",
                "sender" : "amitverma",
            }
        }
    },
    "_id" : ObjectId("5273d09ab743db7a5f000001")
}
我不能使用 $push 或 $addToSet 因为它不是一个数组。或者我可以吗?
另外,我现在有以下代码:
var pushNotification = {};
    var addon = {};
    var anotheraddon = {};
    var utcTime = arrayOps.encodeTime();
    addon[data.sender] = [];
    anotheraddon[utcTime] = data;
    addon[data.sender].push(anotheraddon);
    // var a = pushNotification;
    // a.push(anotheraddon);
    // console.log(pushNotification);
    pushNotification['messages'] = {}
    pushNotification['messages'][data.sender] = [];
    pushNotification['messages'][data.sender] = data;
    var a = 'messages.' + data.sender + '.$';
    console.log('push object');
    console.log(pushNotification);
    co_notifications.update(
        {'username': data.to}, 
        { $addToSet: pushNotification}, function(err, docs){
            console.log(err);
            console.log(docs);
            if (docs == 0){
                co_notifications.insert(
                    {'username': data.to, 'messages': addon}, function(er, doc){
                });
            }
        },
        {upsert: true}
    );
原谅垃圾代码。上面的代码导致了这个结构:
{
    "username" : "macbook",
    "messages" : {
        "amitverma" : [
            {
                "1383321755" : {
                    "to" : "macbook",
                    "message" : "hi.",
                    "sender" : "amitverma",
                }
            }
        ]
    },
    "_id" : ObjectId("5273d09ab743db7a5f000001")
}
这不是我想要的。
有没有一种方法可以创建我想要的结构并轻松读取和更新?谢谢。