如何在nodejs中将字符串作为参数转换为集合模型? 所以当有人访问example.com/? table=products,我想访问products集合.我该怎么做?

route.get("/products", async (req, res) => {

    var symbol = req.query.symbol;
    if (symbol == null) {
        res.json({ 'status': 'fail', 'msg': 'symbol not found' });
        return;
    }
    const sampleScheme = new mongoose.Schema({
        price : String
    }, {versionKey : false, strict: false});
    
    
   let model = await db.model(symbol, sampleScheme);
   var data = await model.find();
    return res.json({ 'status': 'success', 'data': data });
});

    

推荐答案

const mongoose = require('mongoose');
const express = require('express');
const route = express.Router();

// Assuming 'db' is your MongoDB connection
// You need to set up your MongoDB connection before using this route

route.get("/products", async (req, res) => {
    const symbol = req.query.symbol;

    if (!symbol) {
        return res.json({ 'status': 'fail', 'msg': 'symbol not found' });
    }

    try {
        // Check if the collection exists in MongoDB
        const collectionExists = await mongoose.connection.db.listCollections({ name: symbol }).hasNext();

        if (!collectionExists) {
            return res.json({ 'status': 'fail', 'msg': 'collection not found' });
        }

        // Define schema for the dynamic model
        const sampleSchema = new mongoose.Schema({
            price: String
        }, { versionKey: false, strict: false });

        // Create or retrieve the dynamic model
        let model = mongoose.models[symbol] || mongoose.model(symbol, sampleSchema);

        // Query the collection using the dynamic model
        const data = await model.find();

        return res.json({ 'status': 'success', 'data': data });
    } catch (error) {
        console.error(error);
        return res.status(500).json({ 'status': 'error', 'msg': 'Internal server error' });
    }
});

module.exports = route;

Node.js相关问答推荐

如何在Firebase Cloud Function v2计划函数中设置代码中的时区?

如何在套接字对象中存储或添加数据?

yarn 安装失败,因为 node-gyp 正在寻找过时的 node 版本标头

为什么 client.on("messageCreate") 的 TextChannel 中缺少 nsfw 属性?

在快速路由中使用 axios 会在数据字段中返回特殊字符而不是 json

如何为单个 mongo nodejs 驱动程序找到最佳连接池大小

如何在没有云功能的情况下使用 Google PubSub

从数据库读取数据并将其作为可下载的 zip 文件发送

如何调用同名的两个函数?

如何使用来自前一阶段的另一个数组的聚合mongoose 在数组中添加字段

带权限的机密 Rest-Api - 总是 403 - 我做错了什么?

如何更改NodeJS中的堆栈大小限制?

node_modules 中 .bin 文件夹的用途是什么?

将 myproject/.npmrc 与注册表一起使用

Dart 语言比 JavaScript (Node.js) 有什么好处

代理后面的凉亭

如何在 MongoDB 中查询引用的对象?

Puppeteer 记录在 page.evaluate

我应该如何在 webpack 中使用时刻时区?

如何在express 中设置默认路径(路由前缀)?