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;