0

For some reason, I can't get the following to work return a document queried from my mongodb database using the node.js driver.

function findSomething(){
  const database = "learning";
  const collection = "stuff";
  var str;

   MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db(database);
    dbo.collection(collection).findOne({}, function(err, result) {
      if (err) throw err;
      str = result.name;
      db.close();
    });
  });
  return str;
}

console.log(findSomething());

This outputs

undefined

However, if I modify my above code to include the following

console.log(str);

right after

str = result.name;

It will result in the following output:

undefined
Company Inc //sample data from my document

The two things I don't understand are;

  1. Why I can't assign str outside the .connect() function, and why the value it is assigned is lost once the connection is closed
  2. Why the .connect() function executes after a value is returned by the findSomething() function.

I understand that my second concern will answer my first, and I am trying to do this so I can modularize my mongodb crud functions so as to make everything cleaner in my express app.

1 Answers1

0

Are you looking something like this code below:

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

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

class MongoDB {
  async connection(connection, options = {}) {
    try {
      const client = await MongoClient.connect(connection.URI, options);
      const db = await client.db(connection.DB);
      MongoDB.db = db;
      MongoDB.client = client;
    } catch(ex) {
      console.log(ex.message);
    }
  }
}

MongoDB.db = {};
MongoDB.client = {};

class MongoModel extends MongoDB {
  constructor(collectionName) {
    super();
    this.collectionName = collectionName;
  }

  get collection() {
    return MongoModel.db.collection(this.collectionName)
  }
}

// get mongodb, for an example: import from another file
const mongodb = new MongoDB();
// connect to mongodb from 'server.js' or 'app.js'
mongodb.connection({ URI: 'mongodb://localhost:27017', DB: 'blog_dev'}, { useUnifiedTopology: true });

const somethingModel = new MongoModel('something');
// an example another collection
const anotherModel = new MongoModel('anotherCollection'); 

// model find
async function findSomething() {
  try {
    const result = await somethingModel.collection.find({}).toArray();

    return result;
  } catch(ex) {
    console.log(ex.message);
  }
}

// model create
async function createSomething(payload) {
  try {
    const result = await somethingModel.collection.insert(payload);
    return result.ops[0];
  } catch(ex) {
    console.log(ex.message);
  }
}

// get controller
app.get('/', async (req, res) => {
  try {
    const result = await findSomething();
    console.log(result);
    res.status(200).send(result);
  } catch(ex) {
    console.log(ex.message);
  }
});

// create controller
app.post('/', async(req, res) => {
  try {
    const result = await createSomething(req.body);
    res.status(200).send(result);
  } catch(ex) {
    console.log(ex.message);
  }
})

app.listen(3000, () => console.log('Server is up on port 3000'));

There's an example simple express server using mongodb. For Advance MongoModel, you can install and learn that code in node-modules.

I hope it can help you to get a new idea.

Titus Sutio Fanpula
  • 3,467
  • 4
  • 14
  • 33