Skip to content

Instantly share code, notes, and snippets.

@alexhgian
Last active August 29, 2015 14:25
Show Gist options
  • Select an option

  • Save alexhgian/97f94f84f0fbe4a033dc to your computer and use it in GitHub Desktop.

Select an option

Save alexhgian/97f94f84f0fbe4a033dc to your computer and use it in GitHub Desktop.
var expect = require('expect.js');
var mongoose = require('mongoose');
/*******************************************************
* Setup Mongoose
*******************************************************/
mongoose.connect("mongodb://localhost/mocha_test");
var testSchema = new mongoose.Schema({
firstName: String,
dob: { type: Date, max: new Date()}
});
var Test = mongoose.model('Test', testSchema);
/*******************************************************
* Begin Mocha Tests
*******************************************************/
describe('Mongoose Validation', function(){
// Clean Up the Tests DB and Seed DB
before(function(done){
Test.find({}).remove(function(){
Test.create({
firstName : 'Alex'
});
done();
});
});
/*******************************************************
* Tests Date
*******************************************************/
describe('Date of Birth', function(){
// Using findOne and save to trigger validator, which works
it('should save using findOne and save method', function(done){
Test.findOne({firstName : 'Alex'}, function (err, doc) {
// Check for error
if(err){
var errMsg = err.errors;
expect(countObj(errMsg)).to.equal(0);
done();
return err;
}
// Adding date to the document
var d = new Date('1/1/2016');
doc.dob = d;
// Save the updated document
doc.save(function( sErr, sDoc ){
// Check for error
if(sErr){
var errMsg = sErr.errors;
expect(countObj(errMsg)).to.equal(0);
}
done();
})
});
});
// Using update and set to trigger validator, should work but doesnt
it('should save using update and $set method', function(done){
// Adding date to the document
var d = new Date('1/1/2016');
// Update document
Test.update({firstName : 'Alex'}, { $set: { dob: d} }, { runValidators:true }, function (err, doc) {
if(err){
var errMsg = err.errors;
expect(countObj(errMsg)).to.equal(0);
done();
return err;
}
done();
});
});
});
// Show the changes
after(function(done){
Test.find({}, function(err, data){
console.log('Database Results:')
console.log(data);
done();
});
});
});
function countObj(obj){
var numOfErrors = 0;
for( key in obj ){
// console.log(' >>> '+obj[key].message)
numOfErrors++;
}
return numOfErrors;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment