Created
September 6, 2012 16:57
-
-
Save aheckmann/3658511 to your computer and use it in GitHub Desktop.
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'); | |
mongoose.connect('localhost', 'testing_1088'); | |
mongoose.connection.on('error', function () { | |
console.error('connection error', arguments); | |
}); | |
var schema = new Schema({ | |
title: String | |
, slug: String | |
, _id: String | |
}); | |
// custom setter | |
schema.path('title').set(function (v) { | |
this.slug = slugify(v); | |
this._id = idify(this.slug); | |
return v; | |
}); | |
function slugify (v) { | |
return (v || '').replace(/\s+/g, '') | |
} | |
function idify (v) { | |
return 'mycustomid_' + v | |
} | |
var A = mongoose.model('A', schema); | |
mongoose.connection.on('open', function () { | |
var a = new A({ title: 'try 1' }); | |
console.log(a); // { title: 'try 1', _id: 'mycustomid_try1', slug: 'try1' } | |
a.save(function (err, a) { | |
if (err) return done(err); | |
A.findById(a._id, 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(); | |
}); | |
} |
Awesome solution to autogenerate fields on a schema.
I used it with node-uuid to generate complex it :)
Thanks for the code, a suggestion: you should replace (v || '')
in slugify()
function by something like (v || randomStringValue)
. This will greatly reduce the risks of collision of two ids.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice