2017-12-18 315 views
0

我正在編寫一個使用javascript,node,mongoDB和mongoose的小應用程序。我有兩個集合;用戶和組,其中每個組包含用戶用嵌套對象編寫測試時Mogoose驗證錯誤

用戶的數組:{_ ID:{類型:字符串,必需:真}姓:{類型:字符串,必需:真},..}

組{ _id:{type:String,required:true},users:[{user:userSchema}]}

我正在使用Mocha和Superagent編寫api單元測試。當我爲包含用戶的嵌套對象的組插入示例文檔時,出現驗證錯誤?

您能否讓我知道這個例子出了什麼問題?

var userSchema = 
{ 
    _id: { 
     type: String, 
     required: true, 
    }, 
    profile: { 
     firstName: { 
      type: String, 
      required: true 
     }, 
     lastName: { 
      type: String, 
      required: true 
     } 
}; 

var GroupSchema = 
{ 
    _id: { 
     type: String, 
     required: true 
    }, 
    users:[{ 
     user: User.userSchema 
    }] 
}; 
it('can query group by id', function(done) { 
    var users = [ 
    { _id: 'az', profile: {firstName: 'a', lastName: 'z'}}, 
    { _id: 'bz', profile: {firstName: 'b', lastName: 'z'}}, 
    ]; 

    User.create(users, function(error, users) { 
    assert.ifError(error); 
    Group.create({ _id: 'ab', users: [{ _id: 'az', profile: {firstName: 'a', lastName: 'z'}}, { _id: 'bz', profile: {firstName: 'b', lastName: 'z'}}] }, function(error, doc) { 
    assert.ifError(error); 
    var url = URL_ROOT + '/api/groups/id/ab'; 

    superagent.get(url, function(error, res) { 
     assert.ifError(error); 
     var result; 
     assert.doesNotThrow(function() { 
     result = JSON.parse(res.text); 
     }); 
     assert.ok(result.group); 
     assert.equal(result.group._id, 'ab'); 
     done(); 
    }); 
    }); 
    }); 
}); 

錯誤消息:

Uncaught ValidationError: ChatGroup validation failed: users.1._id: Cast to ObjectID failed for value "bz" at path "_id", users.0._id: Cast to ObjectID failed for value "az" at path "_id", users.0.user.profile.lastName: Path `user.profile.lastName` is required., users.0.user.profile.firstName: Path `user.profile.firstName` is required., users.0.user._id: Path `user._id` is required., users.1.user.profile.lastName: Path `user.profile.lastName` is required., users.1.user.profile.firstName: Path `user.profile.firstName` is 

回答

0

我覺得你GroupSchema定義是不正確的:

var GroupSchema = 
{ 
    _id: { 
     type: String, 
     required: true 
    }, 
    users:[{ 
     user: User.userSchema 
    }] 
}; 

你使用它在測試users陣列應該有User.userSchema數組類型的方法:

var GroupSchema = 
{ 
    _id: { 
     type: String, 
     required: true 
    }, 
    users:[{ 
     type: User.userSchema // type, not 'user' 
    }] 
    // OR just: users: [User.userSchema] 
}; 

否則,如果你仍然需要使用你原來的模式,那麼在您的測試,你應該使用這種方式:

var users = [ 
    { user: { _id: 'az', profile: {firstName: 'a', lastName: 'z'}} }, 
    { user: { _id: 'bz', profile: {firstName: 'b', lastName: 'z'}} }, 
    ]; 
+0

非常感謝,這個變化工作得很好。 「或者只是:用戶:[User.userSchema]」。 – Student