代码之家  ›  专栏  ›  技术社区  ›  Junior

如何在猫鼬中调用动态集合?

  •  0
  • Junior  · 技术社区  · 2 年前

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

    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 });
    });
    
        
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   btm me    2 年前
    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;