Last active
August 29, 2015 13:57
-
-
Save CatTail/9543802 to your computer and use it in GitHub Desktop.
Handy script to auto generate mongoose schema from existing data
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
var prefix = Math.random(); | |
function parse(obj) { | |
var key, value, type, schema; | |
type = obj.constructor.name; | |
switch (type) { | |
case 'Object': | |
schema = {}; | |
for (key in obj) { | |
value = parseKey(key, obj); | |
if (value !== undefined) schema[key] = value; | |
} | |
return schema; | |
case 'Array': | |
value = parseKey(0, obj); | |
schema = []; | |
if (value !== undefined) schema.push(value); | |
return schema; | |
default: | |
return prefix + type; | |
} | |
} | |
function parseKey(key, obj) { | |
var type; | |
if (obj[key] !== undefined) { | |
type = obj[key].constructor.name; | |
switch (type) { | |
case 'Object': | |
case 'Array': | |
return parse(obj[key]); | |
default: | |
return prefix + type; | |
} | |
} | |
} | |
function stringToConstructor(schema) { | |
var str = JSON.stringify(schema); | |
return str.replace(new RegExp('"' + prefix + '(\\S+?)"', 'g'), '$1'); | |
} | |
console.log(stringToConstructor(parse(require('./book-isbn')))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can then use something like js beautify to pretty print you schema