2015-05-07 97 views
0

我有以下的模型模式:保存模型貓鼬無法保存嵌套的組件

var memberSchema = mongoose.Schema({ 

    'project'  : { 
     'type'  : Schema.Types.ObjectId, 
     'ref'  : 'Project' 
    }, 
    'first'   : String, 
    'last'   : String, 
    'email'   : String, 
    'tracker'  : { 
     'etag'  : String, 
     'id'  : String, 
     'photoLink' : String, 
     'role'  : String, 
     'type'  : String, 
         }, 
    'survey'  : { 
     'etag'  : String, 
     'id'  : String, 
     'photoLink' : String, 
     'role'  : String, 
     'type'  : String, 
         }, 

}); 

我要保存新文檔。我執行以下操作:

var Member  = require('../app/models/member'); 

var new_member = new Member({ 
    project  : project._id, 
    first  : req.body.all_perms[i].first, 
    last   : req.body.all_perms[i].last, 
    email  : req.body.all_perms[i].email, 
    tracker  : { 
        etag  : req.body.all_perms[i].etag_tracker, 
        id  : req.body.all_perms[i].ftid_tracker, 
        photoLink : req.body.all_perms[i].photoLink_tracker, 
        role  : req.body.all_perms[i].role_tracker, 
        type  : req.body.all_perms[i].type_tracker, 
       }, 
    survey  : { 
        etag  : req.body.all_perms[i].etag_survey, 
        id  : req.body.all_perms[i].ftid_survey, 
        photoLink : req.body.all_perms[i].photoLink_survey, 
        role  : req.body.all_perms[i].role_survey, 
        type  : req.body.all_perms[i].type_survey, 
       }, 
}) 
new_member.save(function(err, saved_result) {}) 

在成功創建新的文件執行此操作的結果,但該文件不包含任何trackersurvey。但是,它包含first,lastemail

如何成功保存新模型的嵌套組件?謝謝。

回答

1

要定義名爲type的嵌入式對象中的字段,您需要使用對象表示法來定義其類型,或者Mongoose認爲它定義了父對象的類型。

所以你的模式更改爲:

var memberSchema = mongoose.Schema({ 

    'project'  : { 
     'type'  : Schema.Types.ObjectId, 
     'ref'  : 'Project' 
    }, 
    'first'   : String, 
    'last'   : String, 
    'email'   : String, 
    'tracker'  : { 
     'etag'  : String, 
     'id'  : String, 
     'photoLink' : String, 
     'role'  : String, 
     'type'  : {'type': String}, // Here... 
    }, 
    'survey'  : { 
     'etag'  : String, 
     'id'  : String, 
     'photoLink' : String, 
     'role'  : String, 
     'type'  : {'type': String}, // ...and here 
    }, 
});