如何在mongoose中调用动态集合?

nnt7mjpx  于 11个月前  发布在  Go
关注(0)|答案(1)|浏览(78)

如何在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 });
});

字符串

ne5o7dgx

ne5o7dgx1#

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;

字符串

相关问题