0

I don't know much Javascript and was making a nodejs app. My mongodb query in nodejs is working only when the query has a function method like .toArray

Here's the database.js file

const {MongoClient} = require('mongodb');

const uri = "mongodb+srv://name:pass@clusterurl/metro4?retryWrites=true&w=majority";
// all fields are correctly filled


const client = new MongoClient(uri);

  try {
      // Connect to the MongoDB cluster
      client.connect(err =>{
        if(err) throw err;

        let db = client.db('metro4');

        db.collection('Station').find().toArray(function(err, result){
          if(err) throw err;
          console.log(result);
        });
        
        let a = db.collection('Station').findOne({'_id':4});
        if(a) {
          console.log(a);
        }
        else{
          console.log("No a\n");
        }

        module.exports = db;

      });

  } catch (e) {
      console.error(e);
  } finally {
      client.close();
  }

when I run the app, the db.collection('Station').find().toArray runs fine and output the result but the second query of findOne doesn't work.

Any help is appreciated.

1 Answer 1

1

The findOne method returns a Promise. You should handle its result in a callback function:

db.collection('Station').findOne({ _id: 4 }, function (err, a) {
  if (err) {
    console.log(err);
  } else if (a) {
    console.log(a);
  } else {
    console.log('No a\n');
  }
});

Or using async - await:

client.connect(async (err) => {
    ...

    let a = await db.collection('Station').findOne({ _id: 4 })

    ...
});

EDIT To handle the import - export problem you should handle the datase connection operations separate async functions.
You may use the connection function to return the database instance:

const {MongoClient} = require('mongodb');

const uri = "mongodb+srv://name:pass@clusterurl/metro4?retryWrites=true&w=majority";
// all fields are correctly filled

const client = new MongoClient(uri);

const connectDB = async () => {
    try {
        // Connect to the MongoDB cluster
        await client.connect();
        return client.db('metro4');
    } catch (e) {
        throw e;
    }
}

const disconnectDB = () => {
    client.close();
}

module.exports = { connectDB, disconnectDB };

Then use these functions to handle your database related operations:

const { connectDB, disconnectDB } = require('../database');

const getStations = async () => {
    const db = connectDB();
    if (!db) return;
    try {
        const data = await db.collection('Station').find().toArray();
        return data;
    } catch (err) {
        throw err;
    } finally {
        disconnectDB();
    }
}

const getStation = async (id) => {
    const db = connectDB();
    if (!db) return;
    try {
        const data = await db.collection('Station').findOne({ _id: id});
        return data;
    } catch (err) {
        throw err;
    } finally {
        disconnectDB();
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

This worked fine. But when I did module.exports = db and then in some other file var client = require('../database');. Now, this same query doesn't work.
@mr.loop See if the edited answer helps
Thanks. Although I figured out I was doing module.exports in the wrong place. Removed all try and catch and doing export at end solved the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.