mongoose-types
mongoose-types copied to clipboard
Not able to validate emails within an array
U have a schema where the user has an array of emails. I want to validate that each of these items are valid/invalid. But there are not getting validated. Please see the mocha,should test code here:
require.paths.unshift('./node_modules'); require('should'); var assert = require('assert');
var mongoose = require('mongoose') , Schema = mongoose.Schema , mongooseTypes = require("mongoose-types") , db = mongoose.createConnection(getMongoUrl());
mongooseTypes.loadTypes(mongoose);
var Email = mongoose.SchemaTypes.Email;
/* if we use the below code.. we get: CALL_NON_FUNCTION_AS_CONSTRUCTOR exception
var emailType = mongoose.SchemaTypes.Email; var Email = new mongoose.Schema({ type: emailType, unique: true, required: true, lowercase: true });
*/
describe('Schema with just one email; Simple User with an invalid email', function(){ var UserSchema = new Schema({ email: Email }); var User = db.model('User', UserSchema); //User.remove({}, function (err) {});
describe('Save invalid email', function(){ it('should throw vaidation error', function(done){ var user = new User({email: 'asdf.com'}); user.save(function(err){ err.message.should.equal('Validation failed'); done(); }); }) }) });
describe('Schema with an ARRAY of emails; User with 1 or more invalid emails', function(){ var UserSchema2 = new Schema({ emails: [Email] }); var User2 = db.model('User2', UserSchema2);
describe('Save invalid email', function(){ it('should throw vaidation error', function(done){ var user2 = new User2({emails: ["rrr"]}); user2.save(function(err){ console.log(err); assert.exist(err); assert.exist(err.message); assert.equal(err.message, 'Validation failed'); done(); }); }) }) });
function getMongoUrl() { if (process.env.VCAP_SERVICES) { var env = JSON.parse(process.env.VCAP_SERVICES); var obj = env['mongodb-1.8'][0]['credentials']; } else { var obj = { "hostname": "localhost", "port": 27017, "username": "", "password": "", "name": "", "db": "" } } obj.hostname = (obj.hostname || 'localhost'); obj.port = (obj.port || 27017); obj.db = (obj.db || 'test');
if (obj.username && obj.password) {
return "mongodb://" + obj.username + ":" + obj.password + "@" + obj.hostname + ":" + obj.port + "/" + obj.db;
} else {
return "mongodb://" + obj.hostname + ":" + obj.port + "/" + obj.db;
}
}
//to run.. mocha <testfile.js>