Created
November 30, 2012 04:18
-
-
Save jwietelmann/4173744 to your computer and use it in GitHub Desktop.
Hack to fake single subdoc field in a mongoose schema
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
// mongoose doesn't like single embedded schemas | |
// it likes them as arrays of an embedded schema | |
// so this is a cheater hack to fake a single subdoc | |
// it creates a field named `_yourField` and a virtual named `yourField` | |
// and it makes sure the array keeps just one element in it | |
// USAGE EXAMPLE: | |
/* | |
var models = require('models') | |
, ChildSchema = models.ChildSchema | |
, singleSubdoc = require('mongoose-single-subdoc'); | |
; | |
var ParentSchema = new Schema({ _child: [ChildSchema] }); | |
ParentSchema.plugin(singleSubdoc, { | |
child1: ChildSchema, | |
child2: ChildSchema | |
}); | |
*/ | |
module.exports = function(schema, fields) { | |
for(var virtualName in fields) { | |
var realName = '_' + virtualName; | |
var schemaType = fields[virtualName]; | |
schema.add({ realName: schemaType }); | |
schema.virtual(virtualName) | |
.get(function() { | |
if(this[realName].length) return this[realName][0]; | |
else return null; | |
}) | |
.set(function(value) { | |
this[realName] = [value]; | |
}) | |
; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment