Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created May 25, 2012 18:27
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aheckmann/2789681 to your computer and use it in GitHub Desktop.
Save aheckmann/2789681 to your computer and use it in GitHub Desktop.
var assert = require('assert')
var mongoose = require('./../mongoose');
console.error(
'\n==========='
, ' mongoose version: '
, mongoose.version
, '========\n\n'
);
var Schema = mongoose.Schema;
mongoose.connect('localhost', 'testing_runtimeDynamicSchemaValidation');
mongoose.connection.on('error', function () {
console.error(arguments);
});
function validate (v) {
switch (this.type) {
case '[Tag]':
return Array.isArray(v) && !! ~v.indexOf('woot')
case 'string':
v = String(v);
return /a-zA-Z/.test(v)
default:
return false
}
}
var schema = new Schema({
type: { type: String }
, value: { type: {}, validate: validate }
});
var A = mongoose.model('A', schema);
mongoose.connection.on('open', function () {
var a = new A;
a.type = 'string'
a.value = '2323';
a.markModified('value');
a.save(function (err) {
assert(err);
a.type = '[Tag]';
a.value = [12,2,3,4,'woot']
a.markModified('value');
a.save(function (err) {
assert.ok(!err, err && err.stack);
A.findById(a, function (err, doc) {
if (err) console.error(err.stack||err);
console.error('found', doc);
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close();
});
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment