Basic node/mongo/mongoose connection not working Basic node/mongo/mongoose connection not working mongoose mongoose

Basic node/mongo/mongoose connection not working


Make it as a callback function after the connection is successfully established. Without it being inside a callback method, it may get executed before the connection to the database is successfully established due to its asynchronous nature.

var mongoose = require("mongoose");mongoose.connect("mongodb://localhost/framework");mongoose.connection.on('connected', function () {    mongoose.connection.db.collectionNames(function (err, names) {        if (err) console.log(err);        else console.log(names);    });})


mongoose.connection.db.collectionNames is deprecated. Use this code to get the list of all collections

const mongoose = require("mongoose")mongoose.connect("mongodb://localhost:27017/framework");mongoose.connection.on('open', () => {  console.log('Connected to mongodb server.');  mongoose.connection.db.listCollections().toArray(function (err, names) {    console.log(names);   });})


If you are not pretty sure of what should be the URL string for your mongoose.connect method. No worries, go to your command prompt, type mongo.

This starts the application where you can see the connection details like

enter image description here

Then use the same URL with your db-name appended like

const mongoose = require('mongoose');mongoose.connect("mongodb://127.0.0.1:27017/db-name").then(    ()=> console.log('connected to db')).catch(    (err)=> console.error(err));