Inheritance in mongoose

后端 未结 5 1181
北海茫月
北海茫月 2021-01-04 01:31

Hello I need to inherit my schemas in mongoose library. Are there complete plugins for that? Or how should I do that myself?

I need to inherit all pre, post, init mi

5条回答
  •  再見小時候
    2021-01-04 02:32

    I know this is an oldie, but I arrived here looking for the answer to the same question and ended up doing something a little different. I don't want to use discriminators because all the documents are stored in the same collection.

    ModelBase.js

    var db = require('mongoose');
    
    module.exports = function(paths) {
        var schema = new db.Schema({ 
            field1: { type: String, required: false, index: false },
            field2: { type: String, required: false, index: false } 
        }, { 
            timestamps: { 
                createdAt: 'CreatedOn', 
                updatedAt: 'ModifiedOn' 
            } 
        });
    
        schema.add(paths);
    
        return schema;
    };
    

    NewModel.js

    var db = require('mongoose');
    var base = require('./ModelBase');
    var schema = new base({
        field3: { type: String, required: false, index: false },
        field4: { type: String, required: false, index: false }
    });
    
    db.model('NewModelItem', schema, 'NewModelItems');
    

    All 4 fields will be in NewModelItem. Use ModelBase for other models where you want to use the same fields/options/etc. In my project I put the timestamps in there.

    Schema.add is called in the Schema constructor so the model should be assembled as if all the fields were sent in the original constructor call.

提交回复
热议问题