Amirhossein
Amirhossein

Reputation: 35

node js return mongodb find results

I can't return mongodb results in function:

find: function (collection,query) {
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url , {keepAlive: 1,useUnifiedTopology: true,useNewUrlParser: true,}, function(err, db) {
  if (err) throw err;
  var dbo = db.db("node");
  dbo.collection(collection).find(query).toArray(function(err, result) {
  if (err) throw err;
  return result;
  db.close();
});
});
}

and in app:

var res = db.find("users",{});

but res is null. please help me... Thank you :)

Upvotes: 1

Views: 1353

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

Here are the quick changes, Try these & also please do enhancements as needed :

1) In a callback way :

db.js :

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

module.exports.find = (collection, query, cb) => {
    let url = "mongodb://localhost:27017/";
    MongoClient.connect(url, { keepAlive: 1, useUnifiedTopology: true, useNewUrlParser: true, }, function (err, db) {
        if (err) cb(err);
        /* Assuming node is your db name where you've collection users */
        const dbo = db.db("node");
        dbo.collection(collection).find(query).toArray(function (err, result) {
            db.close();
            if (err) cb('Pricing err at DB ::', err);
            return cb(null, result);
        });
    });
}

app.js :

const db = require('path to your db file');

db.find("users", {}, (err, res) => {
    if (err) console.log('Printing err ::', err)
    console.log('Printing res ::', res)
});

Or

2) Using async/await way :

db.js :

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

module.exports.find = async (collection, query) => {
    try {
        const url = "mongodb://localhost:27017/";
        const db = await MongoClient.connect(url, { keepAlive: 1, useUnifiedTopology: true, useNewUrlParser: true, })
        /* Assuming node is your db name where you've collection users */
        const dbo = db.db("node");
        const result = await dbo.collection(collection).find(query).toArray();
        db.close();
        return result;
    } catch (error) {
        console.log('Printing error at DB ::', error)
        db.close();
        throw (err)
    }
}

app.js :

const db = require('path to your db file');

class App {

    async dbCall(collectionName, query) {
        try {
            let res = await db.find(collectionName, query);
            return res;
        } catch (error) {
            console.log('Printing error ::', error)
            throw error;
        }
    }
}
module.exports = App;

const controllerObj = new controller();
controllerObj.dbCall('users', {}).then(rs => console.log(JSON.stringify(rs))).catch(err => console.log(err));

Here if your db/collection doesn't exist in your mongoDB then .find() would return [] Vs in case of .findOne() there is no need of .toArray() plus it would return null.

Upvotes: 1

Related Questions