Skip to content

Instantly share code, notes, and snippets.

@CatTail
Last active August 29, 2015 13:57
Show Gist options
  • Save CatTail/9543802 to your computer and use it in GitHub Desktop.
Save CatTail/9543802 to your computer and use it in GitHub Desktop.
Handy script to auto generate mongoose schema from existing data
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'))));
@CatTail
Copy link
Author

CatTail commented Mar 14, 2014

You can then use something like js beautify to pretty print you schema

@qqqzhch
Copy link

qqqzhch commented May 1, 2015

good i like it

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