Select 基于快速路由的 Mongoose 模型
Select Mongoose Model Based on Express Route
我认为这可能是一个基本问题,但正在寻找最佳方法。
我正在构建一个 Express 应用程序,它应该根据路线路由到四种不同的 Mongoose 模型之一。
像这样:
app.get('/:trial', function(req, res){
var trial = req.params.trial;
trial.find(function(err, records) {
if (err)
res.send(err);
res.json(records); // returns all trial records in JSON format
});
});
我有 4 个猫鼬模型,分别命名为:trial1、trial2、trial3、trial4。我想要 URL 的 trial 参数来确定查询哪个集合。显然上面的方法不行,但是我应该怎么做而不是重写四次路由呢?
提前致谢!
您可以通过名称获取模型:
var mongoose = require('mongoose');
app.get('/:trial', function(req, res){
var trial = req.params.trial;
mongoose.Model(trial).find(function(err, records) {
if (err) {
// Return when we end the response here...
return res.send(err);
}
res.json(records); // returns all trial records in JSON format
});
});
根据情况,我会首先验证 trial
的值(例如,请求 /User
不会将所有用户转储到客户端)。
我认为这可能是一个基本问题,但正在寻找最佳方法。
我正在构建一个 Express 应用程序,它应该根据路线路由到四种不同的 Mongoose 模型之一。
像这样:
app.get('/:trial', function(req, res){
var trial = req.params.trial;
trial.find(function(err, records) {
if (err)
res.send(err);
res.json(records); // returns all trial records in JSON format
});
});
我有 4 个猫鼬模型,分别命名为:trial1、trial2、trial3、trial4。我想要 URL 的 trial 参数来确定查询哪个集合。显然上面的方法不行,但是我应该怎么做而不是重写四次路由呢?
提前致谢!
您可以通过名称获取模型:
var mongoose = require('mongoose');
app.get('/:trial', function(req, res){
var trial = req.params.trial;
mongoose.Model(trial).find(function(err, records) {
if (err) {
// Return when we end the response here...
return res.send(err);
}
res.json(records); // returns all trial records in JSON format
});
});
根据情况,我会首先验证 trial
的值(例如,请求 /User
不会将所有用户转储到客户端)。