using MongoClient instead of Mongoose, unable to get passed scoping issues - node.js

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?

Related

Why my function for retrieving data from mongodb is returning undefined?

I am trying to return all the entries from a mongodb collection from a nodejs.
I had written the function and it works if i console log the result i see all the objects from the colletion, but if i try to return the result i am getting undefined.
I cant figure it out why? I had also tried to JSON stringify and JSON parse after but still no success.
Here is my code:
`
const mongoUrl = "mongodb://192.168.8.156:27017/";
const getRoomReadings = function (id) {
MongoClient.connect(mongoUrl, function (err, db) {
if (err) throw err;
let dbo = db.db(`room${id}`);
dbo
.collection("env")
.find({})
.toArray(function (err, result) {
if (err) throw err;
return result;
});
});
};
// API RoomX route
app.get("/api/r:id", (req, res) => {
const rez = getRoomReadings(req.params.id);
console.log(rez);
});
`
I am using nodejs with express.
Please help me. Thanks in advance.
I had also tried to JSON stringify and JSON parse after but still no success.
I don't know why you created the connection each time you do the request but using promises will help you.
Example:
const mongoUrl = "mongodb://192.168.8.156:27017/";
const getRoomReadings = function (id) {
return new Promise((res, rej) => {
MongoClient.connect(mongoUrl, function (err, db) {
if (err) rej(err);
let dbo = db.db(`room${id}`);
dbo
.collection("env")
.find({})
.toArray(function (err, result) {
if (err) rej(err);
return res(result);
});
});
})
};
// API RoomX route
app.get("/api/r:id", async (req, res) => {
const rez = await getRoomReadings(req.params.id);
console.log(rez);
});
a better way to create a connection it creating a file call conn.js and inside that file create your connection
const { MongoClient } = require("mongodb");
const connectionString = process.env.ATLAS_URI;
const client = new MongoClient(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let dbConnection;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
if (err || !db) {
return callback(err);
}
dbConnection = db.db(<db_name>);
console.log("Successfully connected to MongoDB.");
return callback();
});
},
getDb: function () {
return dbConnection;
},
};
initialize the connection and use getDb to get the connection

Retrieving data from mongodb stored by pymongo

I have uploaded data to MongoDB by pymongo and I want to retrieve it in my nodeJs. I am writing function like this but it is not working. my collection name is linux_trace and my database name is Linux_Trace_db.
The error is linux_trace is not defined
const mongoose = require("mongoose")
require('dotenv').config();
const URI = process.env.MONGO_URL;
mongoose.connect(
URI,
(err) => {
if (err) throw err;
console.log('Connected to mongodb');
}
);
linux_trace.find(function (err, adminLogins) {
if (err) return console.error(err);
console.log(adminLogins)})
The issue with your code is that you didn't define linux_trace as a variable in javascript.
To get access to a model in a mongo database that already has a collection, you can run something like this
const query = function (err, adminLogins) {
if (err) return console.error(err);
console.log(adminLogins)};
mongoose.connection.db.collection('linux_trace', function (err, collection) {
collection.find(query).toArray(cb);
});
I got this from this answer: https://stackoverflow.com/a/6721306/3173748

Why is `func` not a function here in node.js?

I am learning mongodb, and in the book, there's a code
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://127.0.0.1:27017/testdb";
module.exports = function (func) {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
else {
console.log("connected");
func(db);
db.close();
}
});
};
I run this code, but throw the error TypeError: func is not a function, I googled, but lots of codes like this, my mongodb version is 4.0, and node.js version is 9.10, any ideas?
Whatever func you are passing must be a function.
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://127.0.0.1:27017/testdb";
module.exports = function (func) { //func must be function, dont pass just a variable
MongoClient.connect(url, function(err, db) {
if (err) throw err;
else {
console.log("connected");
func(db);
db.close();
}
});
};

Mongo DB make connection outside of post?

I am using MongoDB to insert a record into the database, every time the post method is called. I know I do not want to connect to the db inside of the post function every time, but this is giving me errors? How can I correct this?
var mongo = require('mongodb');
var url = 'mongodb://localhost:27017/Wedding'
var db = function() {
mongo.connect(url, function(err, db){
if (!err){
return db;
}
});
}
app.post('/rsvp', function (req, res) {
var item ={
name: req.body.name,
attending: req.body.attending,
};
insertItem(item);
res.sendFile(path.join(__dirname + '/confirm.html'));
})
function insertItem(item){
db.collection('rsvpList').insertOne(item, function(err, result){
assert.equal(null, err);
})
}
I am getting this error:
TypeError: Object function () {
mongo.connect(url, function(err, db){
if (!err){
return db;
}
});
} has no method 'collection'
at insertItem (C:\Users\A587092\Documents\weddingWebsite\server.js:53:8)
at app.listen.host (C:\Users\A587092\Documents\weddingWebsite\server.js:38:4)
at Layer.handle [as handle_request] (C:\Users\A587092\Documents\weddingWebsite\node_modules\express\lib\router\layer.js:95:5)
The problem is your db does not point to the Mongo instance rather to a function!
Try this -
var mongo = require('mongodb');
var url = 'mongodb://localhost:27017/Wedding'
var db;
mongo.connect(url, function(err, connectedDB){
if (!err){
db = connectedDB;
}
});
You couldn't simply return a value from an asynchronous method:
You should use a callback function:
var connectDb = function(url, cb) {
mongo.connect(url, function(err, db){
if ( err ) {
cb( err );
}
cb(null, db);
});
};
Usage:
function insertItem(item) {
connectDb(url, function(error, db) {
if ( error ) {
throw error;
}
db.collection('rsvpList').insertOne(item, function(err, result) {
assert.equal(null, err);
});
});
}
Or a promise:
var connectDb = function(url) {
return new Promise(function(resolve, reject) {
mongo.connect(url, function(err, db){
if ( err ) {
reject(err);
}
resolve(db);
});
});
};
Usage:
function insertItem(item) {
connectDb(url)
.then(function(db) {
db.collection('rsvpList').insertOne(item, function(err, result) {
assert.equal(null, err);
});
}, function(err) {
throw err;
});
}
I change the function name from db to connectDb because we want to connect to db and then doing something after connecting. and this way your code reads well.
Also note that here also your insertItem function doing an asynchronous task so if you need the result outside of this function you should implement a similar approach, i leave it to you ;)

NodeJs - calling one method from another in server controller

With the following controller, how can I call one method from another in the same controller?
Specifically, calling login() within a successful signup(), while retaining the same functionality for login() when it is used by a form?
The line this.login(newUser) does not work, nor does plain old login(newUser)
In both scenarios, I get the error:
TypeError: Cannot call method 'login' of undefined
var mongoskin = require('mongoskin');
module.exports = {
login: (function (req, res) {
req.db.collection('auth').findOne({_id: mongoskin.helper.toObjectID(req.body.id)},
function (err, results) {
// log person in and send results to client
}
)
}),
signup: (function (req, res) {
var user = req.body;
req.db.collection('auth').insert(user, function (err, newUser) {
// after adding user, automatically log them in
// does not work:
//login(newUser, function (err) {
// do something
//})
// does not work:
this.login(newUser, function (err) {
// do something
})
}
)
})
}
Controllers should be doing as little as possible, and should orchestrate the work required by executing functions stored elsewhere.
View this gist - click here
What I have done is created "services" that are not tied to the client request, therefore re-usable everywhere.
Hope this helps.
Thanks to Dave Newton
var mongoskin = require('mongoskin');
var myCollection = 'auth';
Solution
function localLogin(db, myCollection, user, res){
db.collection(myCollection).findOne({_id: mongoskin.helper.toObjectID(user._id)},
function(err, user){
res.send({ token: createToken(user) });
});
module.exports = {
login: (function (req, res) {
var user = req.body;
localLogin(req.db, myCollection, user, res)
},
signup: (function (req, res) {
var user = req.body;
req.db.collection(myCollection).insert(user, function (err, newUser) {
// after adding user, automatically log them in
localLogin(req.db, myCollection, newUser, res)
})
}
) }) }

Resources