Node&Mongoose - 保存时出错:TypeError:在非对象上调用Object.keys

Anc*_*nia 5 mongoose node.js express

在下面的用户模式中有一个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    
        }]
    }

});
Run Code Online (Sandbox Code Playgroud)

这是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) {
        console.log(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;
});
Run Code Online (Sandbox Code Playgroud)

find方法执行成功,但在尝试保存到数据库时抛出以下错误:Error on save: TypeError: Object.keys called on non-object- 任何想法为什么抛出此错误?

此线程有类似的问题,但更改findOnefindById破坏我的用户查询.

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

{  events:
    [ { action: 'updation',
        timestamp: 1408846680,
        user_xid: 'aguxwNqb_Xg87buMyP6Wiw',
        type: 'move',
        event_xid: 'vhAkgg1XwQvLynAkkCc8Iw' } ],
   notification_timestamp: 1408846680 }
Run Code Online (Sandbox Code Playgroud)

以下是该User.findOne方法返回的内容

{ __v: 17,
   _id: 53f7d23e432de20200970c10,
   foobar:
    { id: 'aguxwNqb_Xg87buMyP6Wiw',
      name: 'Test User',
      token: 'W3AjaI7_iOWilcKRpmxenQWi',
      events: [] }
}
Run Code Online (Sandbox Code Playgroud)

Anc*_*nia 5

此错误实际上是由于Mongo数据库中的旧数据.这个events领域充满了额外的弦乐.我删除了这些,我的原始代码开始成功运行.不需要修改上述代码.