skip to Main Content

I’m building a website using react js as front end with node as back end and mongo db as database. I put some dummy data in the database like thissnapshot of mongo db
and im using express and mongoose.created the database in atlas. the db connection is successful and all. but accessing the data within the collection by typing
‘localhost:5000/companies’ on the browser
companies returns connection timed out error always.
my server.js file looks like this

const express=require('express')
const { connectDB,disconnectDB  } = require('./db');
const cors = require('cors');
const Company = require('./models/Company');


var app = express();




// Enable CORS for specific origins
app.use(cors({
    origin: 'http://localhost:3000' // Allow requests from http://localhost:3000
  }));
  

app.get("/api",(req,res)=>{
    res.json({"users":["user1","user2", "user3"]})
})

app.get("/Companies",async (request,response)=>{
    try {
        // Connect to MongoDB (if not already connected)
        await connectDB();

        // Fetch all companies from the companies collection
        const companies = await Company.find();
        
        // Send the list of companies as a JSON response
        response.json(companies);
    } catch (error) {
        // Handle errors
        console.error('Error fetching companies:', error);
        response.status(500).json({ error: 'Internal Server Error' });
    }
    
})

app.listen("5000",()=>{
    console.log("Server is running on port 5000")
});

// Handle graceful shutdown
process.on('SIGINT', async () => {
    try {
        await disconnectDB();
        console.log('Disconnected from MongoDB');
        process.exit(0);
    } catch (error) {
        console.error('Error disconnecting from MongoDB:', error);
        process.exit(1);
    }
});

and my model Company looks like this

// models/Company.js

const mongoose = require('mongoose');

// Define the schema for the Company collection
const companySchema = new mongoose.Schema({
    "_company_name": String,
    "_link": String
    // You can define other fields as needed
});

// Create a Mongoose model for the Company collection
const Company = mongoose.model('companies', companySchema);

module.exports = Company;

and my db.js is

  // db.js
const mongoose = require('mongoose');

require('dotenv').config();

const connectDB = async () => {
   
   try {
       await mongoose.connect('mongodb://localhost:27017/Zien', {
       });
       console.log('db connection success');
   } catch (error) {
       console.error('Error connecting to MongoDB:', error);
   }
};

const disconnectDB = async () => {
   try {
       await mongoose.disconnect();
       console.log('Disconnected from MongoDB');
   } catch (error) {
       console.error('Error disconnecting from MongoDB:', error);
   }
};

module.exports = { connectDB, disconnectDB };

i tried on a locally installed mongodb as provided in the code along with the atlas mongodb string. got same error as output

i tried to reduce the number of documents fetched in one call by changing
const companies = await Company.find().limit(10);
but still no response.but giving the limit(10) do return connection timed out error always.

and i tried to console it like
const result = await Company.find().limit(10).explain(); console.log(result);

and it consoled

Error fetching companies: MongooseError: Operation companies.find() buffering timed out after 10000ms
at Timeout. (D:backendnode_modulesmongooselibdriversnode-mongodb-nativecollection.js:186:23)
at listOnTimeout (node:internal/timers:573:17)
at process.processTimers (node:internal/timers:514:7)

and i tried to convert it to array. like
await Company.find().limit(10).toArray()

and it returned

Error fetching companies: TypeError: Company.find(…).limit(…).toArray is not a function
at D:xampphtdocsemployerratingapplicationviewsmoduleszien-backendserver.js:33:56

help?

3

Answers


  1. try

    Company.find({})
    

    If you are getting timeout from your db and you are sure that there are not that many documents to fetch, it means that it is very likely that your request is not valid. It is possible that you are calling a method incorrectly or you are not returning something. from what you provided find({}) should solve your problem. If not, I’d suggest you to provide more details.

    Login or Signup to reply.
  2. As per the mongoose Model docs:

    The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercased version of your model name.

    Change this:

    const Company = mongoose.model('companies', companySchema);
    

    to this:

    const Company = mongoose.model('Company', companySchema);
    

    Mongoose uses a library to convert your model name to the pluralised version of your model name and use that as the name of your collection.

    Login or Signup to reply.
  3. I always connect to mongoose via:

    const Company = mongoose.model('Company', companySchema, {{schemaName}});

    whereas {{schemaName}} = in your case would just be ‘Company’

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search