Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created September 6, 2012 16:57
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save aheckmann/3658511 to your computer and use it in GitHub Desktop.
Save aheckmann/3658511 to your computer and use it in GitHub Desktop.
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();
});
}
@FvckSh1t
Copy link

nice

@picsoung
Copy link

picsoung commented Apr 1, 2015

Awesome solution to autogenerate fields on a schema.

I used it with node-uuid to generate complex it :)

@top-kat
Copy link

top-kat commented Nov 7, 2023

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