Home > Enterprise >  mongodb method without function not working in nodejs
mongodb method without function not working in nodejs

Time:01-12

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.

CodePudding user response:

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();
    }
}
  •  Tags:  
  • Related