I am writing a small application that uses javascript, node, mongoDB, and mongoose. I have two collections; users and groups where every group contains an array of users
User:{_id:{type: String, required: true} FirstName: {type: String, required: true}, ..}
Group{_id:{type: String, required: true}, users:[{user: userSchema}] }
I am writing an api unit test using Mocha and Superagent. When I insert a sample document for the group that includes a nested objects for the users, I got a validation error?
Could you please let me know what is going wrong with this example?
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();
});
});
});
});
Error Message:
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