Skip to content

Instantly share code, notes, and snippets.

@shalkam
Created February 12, 2017 19:59
Show Gist options
  • Save shalkam/8306bd12c514cd03b86f21cbc516d161 to your computer and use it in GitHub Desktop.
Save shalkam/8306bd12c514cd03b86f21cbc516d161 to your computer and use it in GitHub Desktop.
creating a a custom mongoose schema type
'use strict';
var assert = require('assert');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/db');
mongoose.set('debug', true);
class customType {
constructor(v) {
this.v = v;
}
toBSON() {
return this.v;
}
}
class customTypeSchema extends mongoose.SchemaType {
cast(v) {
return new customType(v);
}
}
mongoose.Schema.Types.customType = customTypeSchema;
const schema = new Schema({ test: customType });
const testing = mongoose.model('test', schema);
testing.create({ test: 5 }).then(doc => {
console.log('done', doc);
console.log(doc.test.toBSON());
process.exit(0);
});
@ManishSymentix
Copy link

mongoose.Schema.Types.customType = customTypeSchema;
this line is not working.
Property 'customType' does not exist on type 'typeof Types'.
I'm using typescript.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment