Last active
December 21, 2015 09:49
-
-
Save aheckmann/6287665 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'); | |
var Schema = mongoose.Schema; | |
var assert = require('assert') | |
console.log('\n==========='); | |
console.log(' mongoose version: %s', mongoose.version); | |
console.log('========\n\n'); | |
var dbname = 'goosetest-1652'; | |
mongoose.connect('localhost', dbname); | |
mongoose.connection.on('error', function () { | |
console.error('connection error', arguments); | |
}); | |
var AddressSchema = Schema({ street: String, city: String, zip: Number }) | |
var schema = new Schema({ | |
name: String | |
, addresses: { type: [AddressSchema], validate: validator } | |
}); | |
function validator (array) { | |
var bad = []; | |
var ok = array.every(function (address) { | |
if (!address.isModified()) return true; | |
if (!address.city /*etc */) { | |
bad.push(address); | |
return false; | |
} | |
return true | |
}) | |
if (!ok) { | |
this.invalidate('addresses', 'missing value', bad) | |
} | |
return true; | |
} | |
var A = mongoose.model('A', schema); | |
mongoose.connection.on('open', function () { | |
var a = new A({ | |
name: '1652' | |
, addresses: [{ street: '5 What Street', city: 'Palo Alto' }] | |
}); | |
a.save(function (err) { | |
if (err) { | |
console.log(err) | |
return done(); | |
} | |
A.findById(a, function (err, doc) { | |
console.log('found', doc); | |
doc.addresses[0].city = ''; | |
doc.save(function (err) { | |
if (err) { | |
console.log(err) // error! | |
return done(); | |
} | |
done(); | |
}) | |
}) | |
}) | |
}); | |
function done () { | |
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