Search code examples
javascriptnode.jsdatabasemongodbmongoose

A wrong query string in MongoDB seems not launch errors


I'm learning Node.js and MongoDB. I'm struggling with this code. I'm connecting to a db called recipe-db with a query string. I don't understand why the catch block isn't triggered if I wrongly change the query string to:

mongoose.connect("mongodb://127.0.0.1:27017/rec-db"); //rec-db doesn't exist but non-error

mongoose.connect("mongodb://127.0.0.1:270/recipe-db"); //no error if I change the port

Error only occurs (in the catch) if I change the mongodb part:

mongoose.connect("moodb://127.0.0.1:27017/recipe-db");

Is it normal this beahavior or I'm wrong?

Another thing is that

database.once("connected", () => {
        console.log("Database connected");
      });

this message isn't printed, may be because I have to link the listener before to call await mongoose.connect and indeed in this way it works. Is it right?

import express from "express";
import mongoose from "mongoose";
import { router as routes } from "./routes/index.js";


const app = express();
let database;

app.use(express.json());

app.use(express.urlencoded({ extended: true }));

//mongodb://127.0.0.1:27017/recipes-db
//npm install mongoose

(async () => {
  await connectToDB();
  console.log("OK");
  
  startServer();
})().catch(() => {
  
  console.log("error connection to db");
});



async function connectToDB() {
  //or mongoose.connect("mongodb://127.0.0.1:27017", { dbName: "recipe-db" })
  //mongoose.connect("mongodb://127.0.0.1:27017/recipe-db");
  await mongoose.connect("mongodb://127.0.0.1:27017/recipe-db");
  database = mongoose.connection;

 
  database.on("error", (error) => {
    console.log("error");
  });

  database.once("connected", () => {
    console.log("Database connected");
  });
}

Solution

    1. MongoDB will create the database on the first use, so there is no Error even if the DB was not already created.

    2. Port change won't give you error immediately, as mongodb driver tries to establish connection. But it will eventually give you timeout error.

    3. You will get error when you provide invalid URI, moodb:// is not the valid string pattern the connect function is expecting thus throws error.

    4. The connected event was already triggered and there was no listener, You added the listener, but the connected was already triggered, thus it will never get called.

    mongoose.connection.once("connected", () => {
        console.log("Database connected");
    });
    
    mongoose.connect("mongodb://localhost/stackoverflow-answer").then(response => {
        console.log("Connection success",);
    }).catch(error => {
        console.log("error on connection");
    })
    

    This gives me output in this sequence:

    Database connected
    Connection success