1

I'm new to MEAN stack development. I've created a database in MongoDB called 'framework' and a collection called 'users' with some json in. I can see that's all there and happy using mongo commands through Mac terminal.

Now I'm writing some Mongoose in my application and to test everything is working, I just want to get a list of the collection names. I tried this:

var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/framework");

mongoose.connection.db.collectionNames(function (err, names) {
  if (err) console.log(err);
  else console.log(names);
});

But when I run that file through the command line, it doesn't log anything at all. What am I doing wrong here?

CaribouCode
  • 13,998
  • 28
  • 102
  • 174

3 Answers3

2

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);
    });
})
BatScream
  • 19,260
  • 4
  • 52
  • 68
2

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);
   });
})
Deepak
  • 293
  • 3
  • 9
1

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)
);

Hope this helps !!

suraj garla
  • 322
  • 3
  • 6