Mongodb delay to provide data by vercel API

I created a simple CRUD project with Reactjs. For the server side, I use Express and Vercel to deploy the server codes. I use MongoDB for a database. In Mongodb I create a database and create 2 collections for relevant usage. However, after deploying the code to Vercel, MongoDB does not provide data suddenly. This means, the vercel API working well. Suddenly, 1 hour or 30 minutes later if I go to the API, then the Mongodb may never hit. After some reloading, I got data from MongoDB. The same issue again after 5 minutes or 10 minutes later.

here are my server-side codes:

const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config()
const jwt = require('jsonwebtoken');
const express = require('express');
const app = express();
const cors = require('cors');
const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json())


const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@ass-11.8xhsqle.mongodb.net/?retryWrites=true&w=majority&appName=AtlasApp`;

// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
    serverApi: {
        version: ServerApiVersion.v1,
        strict: true,
        deprecationErrors: true,
    }
});

// JWT token verify 
const verifyJWT = (req, res, next) => {
    const authorization = req.headers.authorization;
    if (!authorization) {
        return res.status(401).send({ error: true, message: 'unauthorized access' });
    }
    const token = authorization.split(' ')[1];
    jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
        if (err) {
            return res.status(401).send({ error: true, message: 'unauthorized access' })
        }
        req.decoded = decoded;
        next();
    })
}


async function run() {
    try {
        // Connect the client to the server (optional starting in v4.7)
        await client.connect();
        const servicesCollection = client.db('carService').collection('services');
        const bookingCollection = client.db('carService').collection('booking');

        // jwt
        app.post('/jwt', (req, res) => {
            const user = req.body;
            console.log(user);
            const token = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1h' });
            console.log(token);
            res.send({ token });
        })

        app.get('/services', async (req, res) => {
            const options = {
                sort: {
                    service_id: 1
                }
            }
            const cursor = servicesCollection.find({}, options);
            const result = await cursor.toArray();
            res.send(result);
        })
        // load a specific data for booking page
        app.get('/services/:id', async (req, res) => {
            const id = req.params.id;
            const query = { _id: new ObjectId(id) }

            const options = {
                // Include only the `title` and `imdb` fields in the returned document
                projection: { title: 1, price: 1, service_id: 1, img: 1 },
            };

            const result = await servicesCollection.findOne(query, options);
            res.send(result);
        })
        // user all booking show page 
        // bookings routes
        app.get('/userOrder', verifyJWT, async (req, res) => {
            const decoded = req.decoded;

            if (decoded.email !== req.query.email) {
                return res.status(403).send({ error: 1, message: 'forbidden access' })
            }

            let query = {};
            if (req.query?.email) {
                query = { email: req.query.email }
            }
            const result = await bookingCollection.find(query).toArray();
            res.send(result);
        })

        app.post('/addService/:id', async (req, res) => {
            const booking = req.body;
            console.log(booking);
            const result = await bookingCollection.insertOne(booking);
            res.send(result);
        });

        app.patch('/userOrder/:id', async (req, res) => {
            const id = req.params.id;
            const filter = { _id: new ObjectId(id) };
            const updatedBooking = req.body;
            const updateDoc = {
                $set: {
                    status: updatedBooking.status
                },
            };
            const result = await bookingCollection.updateOne(filter, updateDoc);
            res.send(result);
        })

        app.delete('/userOrder/:id', async (req, res) => {
            const id = req.params.id;
            const query = { _id: new ObjectId(id) }
            const result = await bookingCollection.deleteOne(query);
            res.send(result);
        })
        // Send a ping to confirm a successful connection
        await client.db("admin").command({ ping: 1 });
        console.log("Pinged your deployment. You successfully connected to MongoDB!");
    } finally {
        // Ensures that the client will close when you finish/error
        // await client.close();
    }
}
run().catch(console.dir);



app.get('/', (req, res) => {
    res.send('Car repair is running!');
})

app.listen(port, (req, res) => {
    console.log(`${port} listening this site!`);
})

The main issue is why it is taking time or delay to provide data. I checked everything was okay but I did not find out solution. Here is my vercel deploy API link: https://car-solution.vercel.app/services

If you see Cannot GET /services then reload a few times. Then it will show data from MongoDB. this is my problem. Why is data not showing the first time? Why do I need to reload? Kindly help me!!

Hi @Md_Tanvir_Parvej_Badhon,

Welcome to the MongoDB Community :sparkles:

I’ve tested the link you provided, and it seems to be working well on my end. Have you tried accessing it using a different browser, incognito mode, or on another system? I would recommend clearing your browser cache and trying to run the API again. It should work as expected after doing so.

In case the issue persists please feel free to reach out.

Best regards,
Kushagra

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.