使用猫鼬时如何实现工厂模式?
How to implement factory pattern when using 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 请求)我需要创建几种类型的模型:
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); ???
});
我需要了解使用类似模型并从工厂或其他方式创建实例的最佳实践。
请分享您的经验。
您可以使用以下内容从字符串中获取模型:
var mongoose = require('mongoose')
var model = mongoose.model('Unit')
PS:如果这是您问题的解决方案,我想知道您设计数据库模型的方式是否真的正确!您不能创建一个带有索引 "type" 属性 的模型 "Doc" 吗?它在很多方面都会更有效率。
我正在使用 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 请求)我需要创建几种类型的模型:
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); ???
});
我需要了解使用类似模型并从工厂或其他方式创建实例的最佳实践。
请分享您的经验。
您可以使用以下内容从字符串中获取模型:
var mongoose = require('mongoose')
var model = mongoose.model('Unit')
PS:如果这是您问题的解决方案,我想知道您设计数据库模型的方式是否真的正确!您不能创建一个带有索引 "type" 属性 的模型 "Doc" 吗?它在很多方面都会更有效率。