0

I don't need schema validation, so I'd rather not add the weight of Mongoose to my project. Unfortunately, I am unable to find a way in MongoClient; I'm unable to get my function outside of the mongo.connect ({}) scope, so that I can export my callback functions.

const mongo = require('mongodb').MongoClient;
const uri = "mongodb://localhost:27017";

mongo.connect(uri, function (err, db) {
const dbo = db.db("readings");
if (err) {
    throw err;
};
console.log('MongoDB connected...')

function insertReading (data) {
    dbo.collection("myReadings").insertOne(data, function(err, res) {
        if (err) throw err;
        console.log("1 document inserted");
    });    
    };
});

exports.newReading = function(req, res) {
    insertReading(req.body)
};

exports.myDashboard = function (req, res) {
    console.log("test");
}

The "newReading" function would pertain to a POST verb and the "myDashboard" function to a GET verb. Putting my exports inside of the scopes of course will throw errors. How do I get my "insertReading" function to function for my out-of-scope function?

James
  • 25
  • 2
  • 7
  • https://stackoverflow.com/questions/24621940/how-to-properly-reuse-connection-to-mongodb-across-nodejs-application-and-module This answer may have some useful code to demonstrate reusing the connection. Basically you want to set some variable which is globally in-scope to the rest of your modules as the MongoDB connection to your specific database - use that to route to the different collections within and run DB operations – Mikhail Feb 06 '18 at 22:19
  • Can I suggest you use a more simplify option like `mongojs` https://github.com/mafintosh/mongojs – Hassan Sani Feb 06 '18 at 22:59

0 Answers0