Mongoose Module Unable to connect to the database

Currently I’m learning nestjs, and when I’m trying to connect my nestjs to mongodb, I got a problem like this.

// app.module.ts
@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    MongooseModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (config: ConfigService) => {
        const uri = util.format(
          `mongodb://%s:%s@%s:%d/%s`,
          config.get('DB_USERNAME'),
          config.get('DB_PASSWORD'),
          config.get('DB_HOST'),
          config.get('DB_PORT'),
          config.get('DB_NAME'),
        )
        console.log(uri)
        return {
          uri,
        }
      },
    }),
    UsersModule
  ],
  controllers: [
    AppController
  ],
  providers: [
    AppService
  ],
})
export class AppModule { }

the log of the uri is mongodb://username:password@localhost:27017/the-db

but I always got error

[Nest] 25887  - 11/18/2023, 2:24:05 PM   ERROR [MongooseModule] Unable to connect to the database.

or the full log of the program is like this

[Nest] 25887  - 11/18/2023, 2:24:05 PM     LOG [NestFactory] Starting Nest application...
[Nest] 25887  - 11/18/2023, 2:24:05 PM     LOG [InstanceLoader] MongooseModule dependencies initialized +35ms
[Nest] 25887  - 11/18/2023, 2:24:05 PM     LOG [InstanceLoader] ConfigHostModule dependencies initialized +1ms
[Nest] 25887  - 11/18/2023, 2:24:05 PM     LOG [InstanceLoader] AppModule dependencies initialized +0ms
[Nest] 25887  - 11/18/2023, 2:24:05 PM     LOG [InstanceLoader] ConfigModule dependencies initialized +1ms
[Nest] 25887  - 11/18/2023, 2:24:05 PM     LOG [InstanceLoader] ConfigModule dependencies initialized +0ms
mongodb://username:password@localhost:27017/the-db
[Nest] 25887  - 11/18/2023, 2:24:05 PM   ERROR [MongooseModule] Unable to connect to the database. Retrying (1)...
[Nest] 25887  - 11/18/2023, 2:24:08 PM   ERROR [MongooseModule] Unable to connect to the database. Retrying (2)...
[Nest] 25887  - 11/18/2023, 2:24:11 PM   ERROR [MongooseModule] Unable to connect to the database. Retrying (3)...
[Nest] 25887  - 11/18/2023, 2:24:14 PM   ERROR [MongooseModule] Unable to connect to the database. Retrying (4)...
[Nest] 25887  - 11/18/2023, 2:24:17 PM   ERROR [MongooseModule] Unable to connect to the database. Retrying (5)...
[Nest] 25887  - 11/18/2023, 2:24:20 PM   ERROR [MongooseModule] Unable to connect to the database. Retrying (6)...
[Nest] 25887  - 11/18/2023, 2:24:23 PM   ERROR [MongooseModule] Unable to connect to the database. Retrying (7)...
[Nest] 25887  - 11/18/2023, 2:24:26 PM   ERROR [MongooseModule] Unable to connect to the database. Retrying (8)...
[Nest] 25887  - 11/18/2023, 2:24:29 PM   ERROR [MongooseModule] Unable to connect to the database. Retrying (9)...
[Nest] 25887  - 11/18/2023, 2:24:30 PM   ERROR [ExceptionHandler] Authentication failed.
MongoServerError: Authentication failed.
    at Connection.onMessage (/home/damian/projects/youapp/youapp/node_modules/.pnpm/[email protected]/node_modules/mongodb/src/cmap/connection.ts:409:18)
    at MessageStream.<anonymous> (/home/damian/projects/youapp/youapp/node_modules/.pnpm/[email protected]/node_modules/mongodb/src/cmap/connection.ts:239:56)
    at MessageStream.emit (node:events:513:28)
    at processIncomingData (/home/damian/projects/youapp/youapp/node_modules/.pnpm/[email protected]/node_modules/mongodb/src/cmap/message_stream.ts:193:12)
    at MessageStream._write (/home/damian/projects/youapp/youapp/node_modules/.pnpm/[email protected]/node_modules/mongodb/src/cmap/message_stream.ts:74:5)
    at writeOrBuffer (node:internal/streams/writable:392:12)
    at _write (node:internal/streams/writable:333:10)
    at MessageStream.Writable.write (node:internal/streams/writable:337:10)
    at Socket.ondata (node:internal/streams/readable:766:22)
    at Socket.emit (node:events:513:28)

I got authentication failed in the end, so I try to connect the same credentials with the basic nodejs application, and it was connected properly without any error and I could persist data.

  • I’ve changed the mongoose version and it’s nothing but same
  • I’ve changed the localhost to 127.0.0.1 but nothing changed
  • I’ve added ?directConnection=true to the uri but still nothing changed

can somebody tell me what’s going on here?:(

edit:

for your information I’m using

  • @nestjs/mongoose: ^10.0.2
  • mongoose: ^8.0.1

Issue with ‘upper-case’ module in Node.js: ERR_REQUIRE_ESM when using require()

I am facing a problem with the ‘upper-case’ module in my Node.js application. I’m trying to use the upper-case module to convert a string to uppercase, but I’m encountering an error related to ESM and require().

Node.js Version:

Node.js v20.9.0

Code:

var http = require('http');
var uc = require('upper-case');

http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write(uc.upperCase("hello world!"));
    res.end();
}).listen(5000);

console.log('Uppercase Server running...');

Error Message:

Error [ERR_REQUIRE_ESM]: require() of ES Module ... not supported.
Instead, change the require of index.js to a dynamic import().

I have tried using different syntax for require, but the issue persists.
I have checked the ‘upper-case’ module’s documentation and GitHub page for any known issues, but haven’t found a solution.

Match globs in browser-based JavaScript

In browser-based JavaScript, is it possible to perform glob pattern matching?

For illustrative purposes only, I mean a glob like this: **/*.{eot,otf,ttf,woff,woff2}, which could be matched against a URL. Or perhaps something similar to match against a list of files, etc.

To reiterate, this is in the browser: so no Node, npm packages, SPA libraries, etc.

Chat GPT Gratuit : Révolutionnant la Communication Virtuelle?

Les avancées incessantes de l’intelligence artificielle ont donné naissance à une panoplie d’innovations, et parmi elles, le Chat GPT gratuit se distingue comme une percée significative dans le domaine de la communication automatisée.

Visitez notre page d’accueil CHATGPT pour en savoir plus : ChatGPT Francais

Une Technologie d’Envergure
Le Chat GPT, ou Generative Pre-trained Transformer, incarne une classe d’intelligences artificielles pré-entraînées sur d’immenses corpus textuels. Sa capacité à générer du texte dans des contextes divers en fait un atout majeur, désormais accessible gratuitement à tout utilisateur souhaitant exploiter ses fonctionnalités impressionnantes.

Dialogue Virtuel : Puissance Déployée
Bien plus qu’une simple interface de conversation, le Chat GPT gratuit se révèle être un outil polyvalent. Sa capacité à répondre à des questions, générer du contenu ou simuler des échanges naturels en font un partenaire idéal pour les entreprises cherchant à améliorer leur service client et à offrir une assistance instantanée à leurs clients.

en savoir plus sur une autre langue CHATGPT : ChatGPT Deutsch

Applications Multiformes
Les applications du Chat GPT gratuit sont variées. Son intégration sur un site web peut simplifier la gestion des questions fréquentes des visiteurs, réduisant ainsi la charge de travail du support client. De même, il peut être employé pour la création automatisée de contenu, que ce soit pour des blogs, des descriptions de produits, voire même des œuvres littéraires.

Évolution Technologique Permanente
Les Chat GPT gratuits incarnent une technologie en constante évolution. Leur sophistication croissante leur permet de comprendre des requêtes complexes et de fournir des réponses pertinentes. Cette dynamique assure aux utilisateurs des performances toujours plus impressionnantes à mesure que la technologie continue de progresser.

Limites de la Gratuité
Cependant, malgré les avantages indéniables, les Chat GPT gratuits présentent des limites. Leurs versions gratuites peuvent parfois offrir des capacités plus restreintes que leurs homologues payants, et il est crucial de bien saisir ces limitations avant de s’engager.

Conclusion
En somme, le Chat GPT gratuit représente une opportunité captivante pour explorer les potentialités de l’intelligence artificielle en matière de communication et d’assistance virtuelle. Une utilisation avisée de cette technologie peut considérablement améliorer le service client, la génération de contenu et bien d’autres aspects. Toutefois, garder à l’esprit les limites de la gratuité demeure impératif pour un choix judicieux et éclairé des solutions.

Chat GPT gratuit représente une opportunité captivante pour explorer les potentialités de l’intelligence artificielle en matière de communication et d’assistance virtuelle. Une utilisation avisée de cette technologie peut considérablement améliorer le service client, la génération de contenu et bien d’autres aspects. Toutefois, garder à l’esprit les limites de la gratuité demeure impératif pour un choix judicieux et éclairé des solutions.

React-Hook-Form and appending data in server action

I’ve created a form that has user input along with an image that will get uploaded to cloudinary. Using RHF I’ve registered all of my inputs and im using the handleSubmit() function. Im calling a function called submitFormAction. Id like to validate the photo before saving it to my DB. For some reason the only way I can modify formData is if I save the picture as a separate state value.

here’s my code:

const submitFormAction =  async (data) => {

    console.log(data)

    console.log(data.picture?.[0])  <---- I can see the image data :) 
    const image = data.picture?.[0]

    if (!image) return

    const formData = new FormData();

    console.log(formData) 

    formData.append("file", image);
    formData.append(
      "api_key",
      process.env.NEXT_PUBLIC_CLOUDINARY_API_KEY as string
    );
    formData.append("signature", signature);
    formData.append("timestamp", timestamp);
    formData.append("folder", "daycareApp");

    console.log(formData)   <----- this always just returns a blank FormData :( 

any pointers woudld be much appreciated !

Eventlisteners not showing in browser console

I am creating a web application for cesium JS and have structured my project directory as follow:

Project
-node_modules
-public
-css
-data_3d
-Img
-js
-aggregate.js
-Eventlisteners.js
-appCesium, etc
-index.html
-app.js
-package.json
-package-lock.json

settings for app.js:

import express from 'express';
import axios from 'axios';
import cors from 'cors';
const app = express();
app.use(cors());

// Serve static HTML files
app.use(express.static("public"));
// Route for root path for index.html


import {
  extractPhenomenonNameFromDatastreamName,
  formatDatastreamMetadataForChart,
  extractPropertiesFromFormattedDatastreamMetadata,
} from "./public/js/FetchDatastreamsProcessing.js"
import { observationsArr } from './public/js/CleanObsData.js';

// Serve static CSS files
app.use("/public/css", express.static("public/css", { type: "text/css" }));

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
  });

Why can’t I see the console log of event listeners in the browser console
Event listeners script:

import axios from "axios";
import {activate3DTileFeaturePicking} from "./appCesium.js"
import { error } from "console";
const UpdateSelectedOptions = async function(){
const selectElement = document.getElementById('drop-dowm--Buildings-select');

selectElement.addEventListener('change', async function (){
    console.log(selectElement)
    const selectedOptions = this.selectedOptions;
    const optionSelectionArr = [];
    try{
        const response = await axios.get('http://localhost:3300/Things');
        const apiData = response.data.value
    const filteredData =apiData.value.filter(item => Array.from(selectedOptions).some(option=> option.text === item.name));
    optionSelectionArr.push(filteredData)
    // activate3DTileFeaturePicking(filteredData);
    filteredData.forEach(item => activate3DTileFeaturePicking(item))
    return optionSelectionArr;
}catch(error){
    console.error('Error fetching data:',error);
}
})
}
UpdateSelectedOptions();

enter image description here
enter image description here

I restructured the folders to look like what I presented above and I have already tried adding this in html in the script tag as this:

<script>

  `const UpdateSelectedOptions = async function(){
    const selectElement = document.getElementById('drop-dowm--Buildings-select');
    
    selectElement.addEventListener('change', async function (){
        console.log(selectElement)
        const selectedOptions = this.selectedOptions;
        const optionSelectionArr = [];
        try{
            const response = await axios.get('http://localhost:3300/Things');
            const apiData = response.data.value
        const filteredData =apiData.value.filter(item => Array.from(selectedOptions).some(option=> option.text === item.name));
        optionSelectionArr.push(filteredData)
        // activate3DTileFeaturePicking(filteredData);
        // filteredData.forEach(item => activate3DTileFeaturePicking(item))
        console.log(optionSelectionArr);
    }catch(error){
        console.error('Error fetching data:',error);
    }
    })
    }
    UpdateSelectedOptions();<

/script>`

Which works but when I add it as a path (example,<script src="./js/EventListeners.js" defer type="module"></script>) it does’nt show in browser console. I need to be able to see if the Things data array are loaded when I select the buildings and should highlight the 3d objects in cesium when they are clicked

Jdownloader 2 Event Scripter, Connecting to VPN When Download Speeds Are Low

I’m trying to write a script that detects when the download speed is below a certain threshold (in this case, 90kb/s), and then launches a batch file that connects to a random VPN network. The batch file is working perfectly, but this event script is not. It ignores the wait time, and launches the batch file even if there are no files downloading, and when there are multiple files downloading that don’t match the criteria.

// Function to wait for a download to start
function waitForDownloadStart(downloadLink, timeoutMs) {
    var startTime = new Date().getTime();
    
    while (!downloadLink.isStarted() && (new Date().getTime() - startTime) < timeoutMs) {
        // Wait for the download to start
    }
    
    return downloadLink.isStarted();
}

// Flag to indicate whether there is any download over 90kb/s
var anyDownloadOver90KBps = false;

// Check if downloads are running at all
if (isDownloadControllerRunning() && !isDownloadControllerStopping()) {
    var running = getRunningDownloadLinks();
    
    // Loop through all running downloads
    for (var i = 0; i < running.length; i++) {
        var downloadLink = running[i];
        
        // Wait for the download to start (timeout of 30 seconds)
        var downloadStarted = waitForDownloadStart(downloadLink, 30000);
        
        if (downloadStarted && downloadLink.getDownloadDuration() > 30000) {
            // Check if the current speed is below 90kb/s
            if (downloadLink.getSpeed() >= 90 * 1024) {
                // Set the flag to indicate there's a download over 90kb/s
                anyDownloadOver90KBps = true;
                break; // No need to check further, we found one.
            }
        }
    }
}

// Only proceed if there are no downloads over 90kb/s
if (!anyDownloadOver90KBps) {
    var vpnreset = "C:/Program Files/NordVPN/nordvpn_reconnect.bat";
    callSync(vpnreset);
}

Salesman tracking system

I have coordinates recorded every 5 minutes and stored them. I’m using JavaScript, HTML, and CSS to map these locations and display the route on my website. I’m seeking advice on improving my code or if there are better alternatives, especially for implementing free Google Maps. Any help is appreciated!

i need to get a specific string using javascript or jquery

i have a string like this
var x = “/projectx/index.php/Home/index”
i need a function to affect this sring to get an output value:
y = “/projectx/index.php/Home”
means to right trim and remove last word with separator “/”
also means the same function used in PHP
$y = rtrim($x, “/”);

javascript doesn’t have rtrim();

Uncaught SyntaxError Unexpected identifier ‘addEventListener’ [closed]

I made some code that’s returning me this message in the console “Uncaught SyntaxError: Unexpected identifier ‘addEventListener'” and I can’t see what the error is .
Thank you for the help
this is what i wrote:

<style >
        #box{
            width: 200px;
            height: 200px;
            background: blue;
        }

    </style>
    </head>
    <body>
       <div id="box"></div>
       <script >
        const boxDiv = document.getElementById("box");
        
        boxDiv addEventListener("mouseover",function(e) {
            alert("hey");
        });
    </script>

//an alert to pop up with “hey”//

rendering an array of objects with a forEach() method

I’m having issues rendering an array of objects that are produced by a class using a forEach method.

The DOM file store the variables which create elements and fetch the ids from existing elements.

//renderingFile
import { newProjectDiv, projectDom } from "./DOM";
import { Project, Projects } from "./class";

export let projects = new Projects();
let projArr = projects.allProjects;

projArr.forEach(renderProjects);
export function renderProjects(project) {
    const newProjectDiv = document.createElement("div");
    newProjectDiv.classList.add("project-item"); 
    newProjectDiv.textContent = project.name; 
    projectDom.listDiv.append(newProjectDiv);
}

//class

//class for an individual project
export class Project {
    constructor(name) {
        this.name = name;
        this.tasksArr = [];
    }
    nameOfProject() {
        return this.name;
    }
    addTasksToProject(name, dueDate) {
        let newTask = new Task(name, dueDate);
        this.tasksArr.push(newTask);
    }
}
//class for a group of projects 
export class Projects {
    constructor() {
        this.listOfProjects = [new Project("Sample Project")];
    }
    addProjectToList(name) {
        let p = new Project(name);
        this.listOfProjects.push(p);
        return p
    }
    get allProjects() {
       return this.listOfProjects;
    }
    get numOfProjects() {
        return this.listOfProjects.length;
    }
}

Async/Await Fetch POST parameters for text/html

How do I POST parameters for content type text/html without sending it as an object?

Posting using body : {} or body: JSON.Stringify({}) posts data an object. I want data to be posted as individual values.

$(document).on('click', '#update', async () => {
    try {
        const response = await fetch("/getupdate",{
            method:'POST',
            headers:{
                'Content-Type':'text/html; charset=utf-8'
            },
            body: JSON.stringify({
                "country": getCookie("country"),
                "city": getCookie("city").replace(/"/g, ""),
                "action": 1,
                "csrfmiddlewaretoken": $('input[name=csrfmiddlewaretoken]').val()
            }),
        });
    } catch (error){
        console.log(error)
    }
});

Got an object instead of individual values –

{
    "country": "US",
    "city": "Miami",
    "action": 1,
    "csrfmiddlewaretoken": "iLoS4Bsgdyc6EhOtQKiiXrIqr9S1eojdhdyEeClA8qI5ei2WpfQQu1JrduLrbndndR"
}

Expecting individual values –

    "country": "US",
    "city": "Miami",
    "action": 1,
    "csrfmiddlewaretoken": "iLoS4Bsgdyc6EhOtQKiiXrIqr9S1eojdhdyEeClA8qI5ei2WpfQQu1JrduLrbndndR"

How to relate data to a Google place id when locations can have multiple place Ids?

I’m using the Google Maps api in a project. I am relating data in my database to a place in Google Maps using the Google place id (place.place_id) and retrieving that data later when a user clicks on a given location. This has worked well so far, but I noticed a particular location has two place ids. One is returned when clicking on the location zoomed in, the other is returned if you click on the location when zoomed out. The issue is that if said location is clicked on a zoomed out map, I can’t look up my related data with the place id that is returned. The latest documentation does claim that a location may have multiple place ids. I’m looking for any ideas on how to handle this. I thought about storing the other place ids, but I’m not even sure how the code would know about them since the one returned is dependent on something like map zoom level.

Sentry Capture message not sent on Self hosted but sent on Cloud

I have Sentry Self-Hosted which is on version 22, I can’t make work the Sentry on my Vue app with the Self Hosted, my init is something like this

  Sentry.init({
    app,
    dsn: import.meta.env.VITE_SENTRY_DSN,
    integrations: [
      new Sentry.BrowserTracing({
        routingInstrumentation: Sentry.vueRouterInstrumentation(router),
      }),
    ],
    tracePropagationTargets: [import.meta.env.VITE_SENTRY_TARGET],
}

I have a trigger on click which gonna capture the message into Sentry

myTriggerClick() {
 Sentry.captureMessage('on trigger click test')
}

it was sent on Sentry Free Trial Cloud, but when I tried to change the Sentry Self-Hosted, it was nothing showed up,
is that any setting I need to figure out ??

I was not the one who set the Self-Hosted, this sentry has been there which built by SRE,

Split based on dynamic variable and keep separator in array

I need to split an array based on a dynamic separator that will change, and keep the separator in the resulting array.

Consider the following example where I need to:

  • Split const match = 'somethingcatsomethingcatsomethingcat'

  • using the separator const separator = 'cat'

  • and get the following array as a result: ["something", "cat", "something", "cat", "something", "cat"].

Here’s what I’ve tried:

const separator = 'cat'
const match = 'somethingcatsomethingcatsomethingcat'

const standardSplit = match.split(separator)
console.log(standardSplit)
// >> Array ["something", "something", "something", ""]

const withPureRegex = match.split(/(cat)/)
console.log(withPureRegex)
// >> Array ["something", "cat", "something", "cat", "something", "cat", ""]
// This is what I need, without the last element of an empty string.
// But I need to pass in the separator dynamically.

const regex = new RegExp(`/(${separator})/`, 'gi')
const withStringLiteral = match.split(regex)
console.log(withStringLiteral)
// >> Array ["somethingcatsomethingcatsomethingcat"]

I’m no good with regex. I’ve read some articles about escaping in regex, but it seems it’s not necessary within RegExp? I tried many variations of the RegExp with no luck.

There are a good number of questions regarding this, but only few I’ve found that attempt to do it with a dynamic separator. The few questions I found had answers using string literals and RegExp like I have above.

If I needed to do this only once, I would use a non-regex approach, like using the first split method above and then manually looping through to insert the separator as needed. But in this case I’m running this match/replace many times and can’t add more overhead if it could be avoided.