4

I'm using mongoose to work with my MongoDB documents and have thee models:

module.exports = mongoose.model('Doc', mongoose.Schema({
    type: 'doc'
}, collection: "doc");

module.exports = mongoose.model('Folder', mongoose.Schema({
    type: 'folder'
}, collection: "doc");

module.exports = mongoose.model('Unit', mongoose.Schema({
    type: 'unit'
}, collection: "doc");

At some point (on ajax request coming for example) I need to create model at several type:

app.post('/doc/create/:type', function (req, res, next) {
    var type = req.params.type;
    var data = req.body;

    // how to create model based on incoming type here?
    // var model = new Factory.create(type); ???
});

I need to know best practices to work with similar models and create instance from factory or something else.

Please share your experience.

1 Answer 1

1

You can get a model from a string by using something like:

var mongoose = require('mongoose')
var model = mongoose.model('Unit')

PS: If this is the solution to your problems, I'm wondering if the way you are designing your database models is actually the proper one! Can't you create a single model "Doc" with an indexed "type" property? It would be more efficient in many ways.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer. I can't create single model because each other has different fields.
You could just define all the possible fields and then not use them (fields that are 'undefined' are not stored in Mongo by Mongoose)
I don't want to store all possible fields in single model due to separate logic and data. I'm looking for solution to create factory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.