Created
February 12, 2017 19:59
-
-
Save shalkam/8306bd12c514cd03b86f21cbc516d161 to your computer and use it in GitHub Desktop.
creating a a custom mongoose schema type
This file contains 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
'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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
mongoose.Schema.Types.customType = customTypeSchema;
this line is not working.
Property 'customType' does not exist on type 'typeof Types'.
I'm using typescript.