Skip to content

Instantly share code, notes, and snippets.

@madhums
Forked from aheckmann/1088.js
Created May 23, 2013 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madhums/5633321 to your computer and use it in GitHub Desktop.
Save madhums/5633321 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();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment