Skip to content

Instantly share code, notes, and snippets.

@jwietelmann
Created November 30, 2012 04:18
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 jwietelmann/4173744 to your computer and use it in GitHub Desktop.
Save jwietelmann/4173744 to your computer and use it in GitHub Desktop.
Hack to fake single subdoc field in a mongoose schema
// 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