Automatically generating model schemas with NodeJs and Mongoose

Posted: 03-09-2023 | Views: 6
Automatically generating model schemas with NodeJs and Mongoose

Automatically generating model schemas is a bit more complex, as it involves introspecting the data stored in the collections and dynamically generating schema definitions based on that data. While it's possible to do so, keep in mind that automatically generated schemas might not always accurately reflect the structure you desire, as collections can evolve over time.

Here's a high-level outline of how you could approach generating model schemas:

  1. Inspect Collection Data: Retrieve some documents from each collection to analyze their structure and data types. You can use methods like .findOne() to get a representative document.

  2. Determine Schema Structure: Analyze the structure of the retrieved documents to determine the fields and their data types. You'll need to handle primitive data types (string, number, boolean) as well as more complex ones (arrays, embedded documents).

  3. Generate Schema: Based on the analysis, dynamically generate a Mongoose schema with the appropriate fields and data types.

  4. Create Models: Create Mongoose models using the generated schemas.

Please note that this approach might have limitations:

  • It won't handle complex validation rules or custom methods that you might want to define in your schema.
  • The generated schema might not reflect potential relationships between collections.
  • Schema evolution might lead to inconsistencies if the data changes over time.

Here's a simplified example to demonstrate the concept:

const mongoose = require('mongoose');
const MongoClient = require('mongodb').MongoClient;

const uri = 'mongodb://localhost:27017/your-database-name';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

async function connectAndGenerate() {
  try {
    await client.connect();
    console.log('Connected to MongoDB');

    const database = client.db();
    const collectionNames = await database.listCollections().toArray();

    for (const collection of collectionNames) {
      const collectionName =;
      const sampleDocument = await database.collection(collectionName).findOne();

      // Generate Schema based on sampleDocument
      const schemaFields = {};
      for (const key in sampleDocument) {
        schemaFields[key] = typeof sampleDocument[key];
      const modelSchema = new mongoose.Schema(schemaFields);

      // Create Model
      const Model = mongoose.model(collectionName, modelSchema);

      console.log(`Generated Model for ${collectionName}`);
  } catch (error) {
    console.error('Error:', error);
  } finally {


Remember, this is just a starting point. Depending on your needs and data complexity, you might need to adjust the approach and potentially add manual interventions to ensure accurate schema generation.

Add comment