Reputation: 14398
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?
Upvotes: 1
Views: 7002
Reputation: 318
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
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 !!
Upvotes: 1
Reputation: 303
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);
});
})
Upvotes: 2
Reputation: 19700
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);
});
})
Upvotes: 2