melis
melis

Reputation: 1275

Why is the collections empty of my database object?

A 3rd party node module, creates and populates a mongoDB database on localhost. I am trying to use the database and retrieve data from my custom module. Even though I can connect to the database successfully, it shows no collections or documents in the database.

My impression from the Mongoose documentation, first I have to create schemas, then models for mongoDB for every collection I want to use. These models were created in the 3rd party module and the collections I want to use already exist in the database.

As you can tell, I am new to this mongodb+mongoose+nodejs stack. Am I right about creating the schemas and models in the new module - which is a lot of code duplication?or am I missing something?

From mongo shell I do use gtfs then show collections to confirm gtfs database is not empty.

> use gtfs
switched to db gtfs
> show collections
agencies
routes
...

then confirm there are documents in the db as well,

> db.routes.find({'route_id':'6182'}).pretty()
{
    "_id" : ObjectId("562fcf97090e937d06a34e67"),
    "route_id" : "6182",
    "agency_id" : "DDOT",
     ...
}

I connect to the database from my custom module:

var mongoose = require('mongoose');
var mongo_url = 'mongodb://127.0.0.1:27017/gtfs';
//Each connection instance maps to a single database
var db = mongoose.createConnection(mongo_url);
  console.log('db -> ', db);

I read in the mongoose documentation that when you create a connection mongoose directs your connection object either to open or openSet method. So, I know my problem is not creating a db connection object but not opening it.

When I print out the db object it shows the collections attribute empty:

db ->  { connections: 
   [ { base: [Circular],
       collections: {},
       models: {},
       config: [Object],
       replica: false,
       hosts: null,
       host: 'localhost',
       port: 27017,
       user: undefined,
       pass: undefined,
       name: 'gtfs',
       options: [Object],
       otherDbs: [],
       _readyState: 2,
       _closeCalled: false,
       _hasOpened: false,
       _listening: false,
       _events: {},
       db: [Object] } ],
  plugins: [],
  models: {},
  modelSchemas: {},
  options: { pluralization: true } }

Upvotes: 2

Views: 2214

Answers (2)

Suryansh
Suryansh

Reputation: 1

To get list of Collections in particular DataBase.
If you want to see it in Browser you can use Express to send it as a Response.

const mongoose = require('mongoose');
require('dotenv').config()

// MongoDB connection string (DATABASE NAME IS NOT PRESENT IN URI STRING)(For MongoDb Atlas)
const mongoURI = process.env.DATABASE_URI;

// Connect to MongoDB
mongoose.connect(mongoURI);

// Get the default connection
const db = mongoose.connection;


db.once('open', async ()=>{
  //Connect to database whose collections you want to see
  const userdb = await db.useDb('NAME OF DATABSE WHOSE COLLECTION YOU WANT TO SEE');  
  // Use listCollections method to get all Collection and toArray to display collections in Array
  const  data = await userdb.db.listCollections().toArray()
  console.log(data);
})

Upvotes: 0

robertklep
robertklep

Reputation: 203359

It seems to me that it might be easier to use the mongodb driver instead of Mongoose (the latter implements an extra layer on top of MongoDB documents, which is great but usually works better when the database is being populated by Mongoose as well).

An example on how to query the data using mongodb (make sure to run npm install mongodb before running the script):

var MongoClient = require('mongodb').MongoClient;

var url = 'mongodb://localhost:27017/gtfs';

// Connect to the database.
MongoClient.connect(url, function(err, db) {

  // If an error occurred during connect, exit the script by
  // throwing an exception.
  if (err) throw err;

  // Get a reference to the collection.
  var routes = db.collection('routes');

  // Run a query against the `routes` collection.
  var cursor = routes.find({ route_id : '6182' });

  // Read all the results from the cursor and turn them into a JS array.
  cursor.toArray(function(err, documents) {
    if (err) throw err;

    // Output the results as JSON.
    console.log('%j', documents);

    // Close the connection.
    db.close();
  });

});

Inserting a document is documented here.

One thing to consider with pretty much any Node code is that all I/O operations (network/database/file system/etc) are asynchronous, which means that you pass a function that will be called when the I/O operation has completed (or an error occurred).

These calls don't block; in other words, you are merely telling Node to schedule an I/O operation and get back to you when it has finished. However, any code following the code where you tell Node to perform the operation will be executed right after, and not just when the operation has completed.

That's why the code above nests functions in functions.

Upvotes: 2

Related Questions