使用嵌套目标编写测试时出现Mogoose验证错误

时间:2017-12-18 10:31:13

标签: javascript mongodb mongoose mocha superagent

我正在编写一个使用javascript,node,mongoDB和mongoose的小应用程序。我有两个收藏品;每个组包含一组用户的用户和组

用户:{_ id:{type:String,required:true} FirstName:{type:String,required:true},..}

群组{_id:{type:String,required:true},用户:[{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

1 个答案:

答案 0 :(得分: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'}} },
  ];