使用Mongoose&将哈希值推送到嵌套数组表达

时间:2014-08-26 21:25:23

标签: javascript node.js mongodb express mongoose

在下面的用户架构中,有一个foobar.events字段,一个哈希数组,我正在尝试将新哈希值(从API POST请求中接收)推送到。

var userSchema = mongoose.Schema({

    foobar: {
        id           : String,
        token        : String,
        email        : String,
        name         : String,
        events       : [{
            action          : String,
            timestamp       : Date,
            user_xid        : String,
            type            : {type: String},
            event_xid       : String    
        }]
    }

});

以下是Express路线的逻辑:

app.post('/foobar/post', function(req, res) {
    var jb_user_xid  = req.body['events'][0]['user_xid'];
    var jb_timestamp = req.body['events'][0]['timestamp'];
    var jb_action    = req.body['events'][0]['action'];
    var jb_type      = req.body['events'][0]['type'];
    var jb_event_xid = req.body['events'][0]['event_xid'];

    User.findOne({'foobar.id':jb_user_xid}, function(err, user) {
        user.foobar.events.push({
            user_xid: jb_user_xid,
            timestamp: jb_timestamp,
            action: jb_action,
            type: jb_type,
            event_xid: jb_event_xid
        });
        user.save(function(err) {
            if (err){ 
                console.log("Error on save: " + err);
            }
            else {
                console.log("Save successful");
            }
        });
    });

    res.writeHead(200);
    res.end();
    return;
});

findsave执行成功,但哈希本身未保存到数据库中,如日志文件所示:

Mongoose: users.update({ _id: ObjectId("53f7d23e432de20200970c10") }) { '$inc': { __v: 1 }, '$pushAll': { 'foobar.events': [ '[object Object]' ] } } {}

以下是MongoLab中的条目:

{
    "__v": 11,
    "_id": {
        "$oid": "53f7d23e432de202970c10"
    },
    "foobar": {
        "events": [
            "[object Object]",
            "[object Object]",
            "[object Object]",
            "[object Object]",
            "[object Object]"
        ],
        "id": "aguxwNqb_Xg87buMWiw",
        "name": "Test User",
        "token": "W3AjaI7_iOWilcKRpmx"
    }
}

问题:如何将API哈希中的实际内容保存到foobar.events数组中的新哈希?

作为旁注,这是API中req.body返回的内容:

{  events:
    [ { action: 'updation',
        timestamp: 1408846680,
        user_xid: 'aguxwNqb_Xg87buMyP6Wiw',
        type: 'move',
        event_xid: 'vhAkgg1XwQvLynAkkCc8Iw' } ],
   notification_timestamp: 1408846680 }

0 个答案:

没有答案