gpt4 book ai didi

node.js - 使用 Mongoose 时如何实现工厂模式?

转载 作者:可可西里 更新时间:2023-11-01 09:15:14 25 4
gpt4 key购买 nike

我正在使用 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”吗?它在很多方面都会更有效率。

关于node.js - 使用 Mongoose 时如何实现工厂模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28676142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com