Created
May 23, 2013 22:47
-
-
Save aheckmann/5640063 to your computer and use it in GitHub Desktop.
ignore empty strings when setting ObjectIds
This file contains hidden or 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 uri = 'mongodb://localhost/testing_optionalObjectid'; | |
mongoose.connect(uri); | |
mongoose.connection.on('error', function () { | |
console.error('connection error', arguments); | |
}); | |
// | |
// ignore empty strings | |
// | |
function ignoreEmpty (val) { | |
if ("" === val) { | |
return undefined; | |
} else { | |
return val | |
} | |
} | |
var schema = new Schema({ | |
name: String | |
, oid : { type: Schema.ObjectId, set: ignoreEmpty } | |
}); | |
var A = mongoose.model('A', schema); | |
var a = new A({ name: 'optionalObjectid', oid: '' }); | |
a.save(function (err, a) { | |
if (err) return done(err); | |
A.findById(a, function (err, doc) { | |
console.error('found', doc); | |
done(err); | |
}); | |
}) | |
function done (err) { | |
if (err) console.error(err.stack); | |
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