使用mongoose时如何实现工厂模式?

我正在使用mongoose来处理我的MongoDB文档,并有你的模型:

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"); 

在某个时候(例如在ajax请求中)我需要创build几个types的模型:

 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); ??? }); 

我需要知道最佳实践来使用类似的模型,并从工厂或其他东西创build实例。

请分享你的经验。

你可以通过使用类似于string来获得模型:

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

PS:如果这是你的问题的解决scheme,我想知道你devise你的数据库模型的方式是否真的是正确的! 你不能创build一个带有索引“types”属性的单一模型“文档”吗? 这在许多方面会更有效率。