Challenges encountered when adding a fresh entry into a Mongo database with Mongoose

Could someone please clarify why I'm encountering MongooseErrors when trying to connect to my database using localhost:27017, with a buffering timeout after 10000ms? Strangely, this issue doesn't occur if I use 127.0.0.1:27017. Note that I do not have Atlas installed.

Here is the code snippet that triggers the error:

const mongoose = require("mongoose");
    
mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true,});
    
const Cat = mongoose.model('Cat', { name: String });
    
const kitty = new Cat({ name: 'Zildjian' });

kitty.save().then(() => console.log('meow'));

The problem seems to disappear when I switch from using localhost to 127.0.0.1.

Answer №1

If you're looking for information on why your Mongoose connection may be acting up, I recommend checking out the official Mongoose Connections documentation. While it may not provide a definitive answer, it's worth noting that the issue could be related to the operating system you are using.

Additionally, I suggest creating a file called connect.js and including the following code:

import mongoose from 'mongoose';

const connectDB = async (url) => {
  return mongoose.connect(url);
};

export default connectDB;

Next, in your server.js file, you can add the following code:

import app from './app/Application';

const start = async () => {
  try {
    await connectDB("mongodb://127.0.0.1:27017/fruitsDB");
    app.listen(300, () => console.log('Server is listening in port 3000 ...'));
  } catch (error: any) {
    console.log(error);
  }
};

start();

By implementing these steps, you can ensure that your server will not start until a successful database connection has been established.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to create a repetitive pattern using a for loop in Javascript?

I want to create a repeating pattern to color the background, but once i exceeds colors.length, the background color stops changing because, for example, colors[3] does not exist. I need colors[i] to start back at 0 until the first loop is complete. cons ...

Hovering on the navigation bar items triggers special visual effects

Hey there, I'm currently working on a small website and I've run into a tricky issue. I have a navigation bar with dropdowns that should fade in when hovering over the main word on the navigation bar. I've tried various methods but nothing s ...

Using keyboard events such as onkeyup and onblur to simulate keyboard entry in JavaScript

I'm currently working on automating the input of a betting amount on a bookmaker's betslip. Here is the code I'm using: <input id="slip_sgl_stake95274901L" type ="text" onblur="document.betslip.single_stake_onblur(this,'9527490 ...

Altering the location display on an HTML5 map through user selection from a dropdown menu

I'm currently working on a school project that involves coding. I've successfully implemented geolocation code to display the user's location upon page load. Now, I need to add a drop-down box that allows users to select from three additiona ...

Detecting collisions in three.js – a comprehensive guide

Currently, I am working with three.js and have incorporated two mesh geometries into my scene. I am looking for a way to detect collisions if these geometries intersect or would intersect when translated. How can I carry out collision detection using thre ...

Puppeteer: Easily choosing a dropdown selection by its displayed text

When using Puppeteer, you have the ability to choose an option from a dropdown by specifying the value as a parameter: page.select('select#idOfSelect', 'optionValue'); I'm wondering if there is a way to select an option by its te ...

Sending dynamic internationalization resources from Node.js to Jade templates

Looking for a way to show a custom error page to the user in case of an error, but it needs to be internationalized (i18n-ed). Solution: My idea is to validate in node -> if not accepted -> res.render('error', {message: errorMessageNameToo ...

Gif stubbornly refusing to fade out even after the .fadeOut command is called

Having trouble making a gif fade out after the page loads? Here's my attempt so far: I want the overlay, which includes a white background and the gif, to gradually become transparent once the rest of the page is fully loaded. Take a look at the fol ...

Google Maps API displaying empty spots instead of markers

I am facing an issue with my webpage where the Markers are not showing up, despite troubleshooting for many hours. The parsing php file has been confirmed to be working. Below is the code: <script src="https://maps.googleapis.com/maps/api/js">< ...

Navigating through Routing Express and sending data to a template

If I have the following code in my router.get() function, how can I output a template with the data without being able to use res.render()? router.get('/read', function(request, response) { res.send({"result": "Success sent from routes/index ...

Synchronize information between SAP and DataModels within the Django framework

Currently, I am in the process of developing an application using Django for WareHouse Management. The primary application is integrated with SAP Business One. I have access to tables in SAP (MSSQL Server) and now I need to sync the Warehouse Management us ...

Assign an id attribute in KineticJS once the ajax call is successful

I have implemented KineticJS into my MVC application. To retrieve data from the database, I am utilizing ajax calls to web services in the API controller. One of the APIs returns an id that I want to assign to the current Kinetic.Group id attribute upon s ...

An issue has occurred on the server: The response.status function is not recognized as a valid function

import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); export const GET = async (req, response, next) => { try { console.log('Connected to Database via Prisma'); const movies = await prisma.movi ...

Employing reduce method for finding the total of a collection of elements

I am struggling to calculate the cumulative weight of an array of objects with children. However, I believe my approach is flawed. My goal is to display a list of parcels using a searchable dropdown feature. Users should be able to choose parcel categories ...

Detecting a particular cell in SQL Server

I'm trying to figure out a way to prevent a specific user from changing their profile picture in my SQL Server database. I know that typically you can't make a single cell immutable, but is there a workaround using triggers? Although I'm no ...

Unlock the Potential of Spring REST-JWT-JavaScript for Seamless Transitions

In my Java Spring REST back-end, I am implementing a security feature using Json Web Tokens instead of sessions. For the front-end, I plan to use JavaScript and jQuery for sending requests to the back-end, along with HTML. After a successful login, I stor ...

Unable to execute PHP alongside a JavaScript event listener

Using PHP, I am creating a canvas for writing and the text output will appear in a textarea (handled by other functions). There are additional input tags like a title to gather user input. The values from these input tags (title and textarea) will be submi ...

Efficiently populate entities in MongoDB without the need for padding using Spring framework

Within my application, I implemented the use of buckets to store objects. When created, all buckets start empty. Some buckets may reach their maximum capacity of 20 objects in just 2 hours, while others might take up to 6 months to fill up. The size of eac ...

Unable to locate a React component module that has been published

After successfully publishing a React component to NPM, I encountered an issue when trying to use it in another project - I couldn't find the module! Module not found: Can't resolve 'react-subreddit-posts' in '/Users/kyle.calica/C ...

How can I show an item repeatedly with each button click in ReactJS?

Currently, I have a setup where I can display a checkbox and its label upon clicking a button. However, the limitation is that only one checkbox can be displayed at a time. Is there a way to modify this so that I can show multiple checkboxes simultaneous ...