[英]How to implement factory pattern when using mongoose?
I'm using mongoose to work with my MongoDB documents and have thee models: 我正在使用猫鼬处理我的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");
At some point (on ajax request coming for example) I need to create model at several type: 在某个时候(例如,针对ajax请求),我需要创建几种类型的模型:
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. 请分享您的经验。
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! PS:如果这是解决您的问题的方法,我想知道您设计数据库模型的方式是否正确? Can't you create a single model "Doc" with an indexed "type" property?
您无法创建带有索引的“类型”属性的单个模型“文档”吗? It would be more efficient in many ways.
它在许多方面会更有效率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.