Skip to content

Instantly share code, notes, and snippets.

@ankitarora05
Last active August 23, 2024 08:24
Show Gist options
  • Save ankitarora05/85bf734d1b5785329b4dfaff4c40c624 to your computer and use it in GitHub Desktop.
Save ankitarora05/85bf734d1b5785329b4dfaff4c40c624 to your computer and use it in GitHub Desktop.
Generate mongoose schema for your MongoDB database model from dynamic JSON objects with mixed types
const mongoose = require('mongoose');
// Example JSON object with mixed types in arrays
const json = {
"name": "John Doe",
"age": 30,
"email": "[email protected]",
"isActive": true,
"roles": [
{"role": "admin", "level": 1},
{"role": "user", "access": ["read", "write"]}
],
"history": [
{"event": "login", "timestamp": "2024-08-10T12:00:00Z"},
{"event": "purchase", "item": "laptop", "price": 1200}
]
};
// Function to generate Mongoose schema from JSON
function generateSchemaFromJson(json) {
const schemaDefinition = {};
for (const key in json) {
const value = json[key];
if (Array.isArray(value)) {
if (typeof value[0] === 'object' && value[0] !== null) {
// If the array contains objects, use Mixed type
schemaDefinition[key] = [mongoose.Schema.Types.Mixed];
} else {
// If the array contains primitive types
schemaDefinition[key] = [getType(value[0])];
}
} else if (typeof value === 'object' && value !== null) {
// Handle nested objects
schemaDefinition[key] = generateSchemaFromJson(value);
} else {
// Handle primitive types
schemaDefinition[key] = getType(value);
}
}
return new mongoose.Schema(schemaDefinition);
}
// Helper function to determine the type
function getType(value) {
if (typeof value === 'string') {
return String;
} else if (typeof value === 'number') {
return Number;
} else if (typeof value === 'boolean') {
return Boolean;
} else if (value instanceof Date || !isNaN(Date.parse(value))) {
return Date;
} else if (typeof value === 'object') {
return mongoose.Schema.Types.Mixed; // Use Mixed type for complex objects
} else {
throw new Error(`Unknown type for value: ${value}`);
}
}
// Generate the Mongoose schema
const dynamicSchema = generateSchemaFromJson(json);
// Create a Mongoose model
const DynamicModel = mongoose.model('DynamicModel', dynamicSchema);
// Example usage: Create and save a new document
const newDocument = new DynamicModel(json);
newDocument.save()
.then(doc => {
console.log('Document saved:', doc);
})
.catch(err => {
console.error('Error saving document:', err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment