Search code examples
node.jstypescriptmongodbmongooseplugins

Node + Mongo + Typescript: Add Fields to every Document


i've another stupid question with mongodb (mongoose) in a nodejs project with typescript:

Is it possible to add some fields to every Schema without rewriting it in every schema? I know, ich can extend the schema with ...schema.obj notation. But my idea was to add this fields to a plugin and then have it centralized.

i've the problem to extend current schema with generics and can't access the properties.

Has anyone an idea how to solve this? And maybe it is possible that types get passed to the Document-Type that i can access this fields?

Thanks a lot.


Solution

  • You can create BaseSchema like this

    const { Schema } = mongoose;
    
    const baseSchema = new Schema({
        commonField1: {
            type: String,
            required: true
        },
        commonField2: {
            type: Number,
            default: 0
        }
    });
    
    module.exports = baseSchema;
    

    and then use it in your other schemas like

    const mongoose = require('mongoose');
    const Base = require('./base');
    const { Schema } = mongoose;
    
    const extendedSchema = new Schema(
        Object.assign(
            {},
            Base.obj, // Get the fields from the base schema
            {
                additionalField: {
                    type: String,
                    required: true
                }
            }
        )
    )
    
    module.exports = mongoose.model('Extended', extendedSchema);