Can't export user data in node.js using MongoDB - javascript

I can't seem to find a way to export the user data that I get back from the database. When I require it in the other file I get undefined value or empty object. Please help all I want is to export the user info so I can use it in another file.
My auth.js file:
// Modules
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/affinity';
window.$ = window.jQuery = require('jquery');
$(document).ready(function () {
// Look through db for user
// Flters through the db to find the user and their password to authenticate them in.
userInfo = function (db, callback) {
var username = $('#username').val();
var password = $('#password').val();
var users = db.collection('users');
// Searches through each user in the db to find one which meets conitions.
var cursor = users.find({
"username": username
}, {"limit": 1} ).each(function (err, doc) {
if (doc != null) {
if (doc.password === password) {
module.exports.user_data = doc;
window.location.replace(__dirname + '/assets/views/main.html');
} else {
$("#error-hint").css(
'visibility', 'visible'
);
}
} else {
// Skip user if it isn't matching
}
});
}
// Connects to database.
// Inserts all user data to the database.
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Couldn\'t connect to the mongoDB server. \nERROR: ' + err);
} else {
var collection = db.collection('users');
// When login button run authUser function
$('#auth-btn').click(function () {
userInfo(db, function () {
db.close();
});
});
}
});
});
My app.js file:
// Modules
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/affinity';
var exported = require("/Users/mac/Desktop/projects/Affinity/assets/scripts/auth.js");
window.$ = window.jQuery = require('jquery');
$(document).ready(function () {
var userInfo = exported;
console.log(userInfo);
MongoClient.connect(url, function (err, db) {
if (err) {
console.log("Wasn't able to connect to mongoDB server. \n" + url);
} else {
console.log("Connection established to " + url);
db.close();
}
});
});
Thank you in advance!

Related

How to use another MongoDB database using Node.js [duplicate]

How do I connect to mongodb with node.js?
I have the node-mongodb-native driver.
There's apparently 0 documentation.
Is it something like this?
var mongo = require('mongodb/lib/mongodb');
var Db= new mongo.Db( dbname, new mongo.Server( 'mongolab.com', 27017, {}), {});
Where do I put the username and the password?
Also how do I insert something?
Thanks.
Per the source:
After connecting:
Db.authenticate(user, password, function(err, res) {
// callback
});
Everyone should use this source link:
http://mongodb.github.com/node-mongodb-native/contents.html
Answer to the question:
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
var db = new Db('integration_tests', new Server("127.0.0.1", 27017,
{auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});
// Establish connection to db
db.open(function(err, db) {
assert.equal(null, err);
// Add a user to the database
db.addUser('user', 'name', function(err, result) {
assert.equal(null, err);
// Authenticate
db.authenticate('user', 'name', function(err, result) {
assert.equal(true, result);
db.close();
});
});
});
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://'+DATABASEUSERNAME+':'+DATABASEPASSWORD+'#'+DATABASEHOST+':'DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
//for local server
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DATABASEHOST+':'+DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
I find using a Mongo url handy. I store the URL in an environment variable and use that to configure servers whilst the development version uses a default url with no password.
The URL has the form:
export MONGODB_DATABASE_URL=mongodb://USERNAME:PASSWORD#DBHOST:DBPORT/DBNAME
Code to connect this way:
var DATABASE_URL = process.env.MONGODB_DATABASE_URL || mongodb.DEFAULT_URL;
mongo_connect(DATABASE_URL, mongodb_server_options,
function(err, db) {
if(db && !err) {
console.log("connected to mongodb" + " " + lobby_db);
}
else if(err) {
console.log("NOT connected to mongodb " + err + " " + lobby_db);
}
});
My version:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://user:pass#dhost:port/baseName', function(err, db) {
if (err) {
console.error(err);
}
var collection = db.collection('collectionName');
collection.find().toArray(function(err, docs) {
console.log(docs);
});
});
I recommend mongoskin I just created.
var mongo = require('mongoskin');
var db = mongo.db('admin:pass#localhost/mydb?auto_reconnnect');
db.collection('mycollection').find().toArray(function(err, items){
// do something with items
});
Is mongoskin sync? Nop, it is async.
Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:
var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
assert = require('assert');
var user = 'user';
var password = 'password';
MongoClient.connect('mongodb://'+user+':'+password+'#localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
if(err){
console.log("Auth Failed");
return;
}
console.log("Connected");
db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
console.log(doc['_id']);
}
});
});
db.close();
});
This worked for me:
Db.admin().authenticate(user, password, function() {} );
You can do it like this
var db = require('mongo-lite').connect('mongodb://localhost/test')
more details ...
if you continue to have problems with the native driver, you can also check out sleepy mongoose. It's a python REST server that you can simply access with node request to get to your Mongo instance.
http://www.snailinaturtleneck.com/blog/2010/02/22/sleepy-mongoose-a-mongodb-rest-interface/
With the link provided by #mattdlockyer as reference, this worked for me:
var mongo = require('mongodb');
var server = new mongo.Server(host, port, options);
db = new mongo.Db(mydb, server, {fsync:true});
db.open(function(err, db) {
if(!err) {
console.log("Connected to database");
db.authenticate(user, password, function(err, res) {
if(!err) {
console.log("Authenticated");
} else {
console.log("Error in authentication.");
console.log(err);
}
});
} else {
console.log("Error in open().");
console.log(err);
};
});
exports.testMongo = function(req, res){
db.collection( mycollection, function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
Slight typo with Chris' answer.
Db.authenticate(user, password, function({ // callback }));
should be
Db.authenticate(user, password, function(){ // callback } );
Also depending on your mongodb configuration, you may need to connect to admin and auth there first before going to a different database. This will be the case if you don't add a user to the database you're trying to access. Then you can auth via admin and then switch db and then read or write at will.
const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myProject';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
// the following code examples can be pasted here...
return 'done.';
}
main()
//what to do next
.then(console.log)
//if there is an error
.catch(console.error)
// what to do in the end(function result won't matter here, it will execute always).
.finally(() => client.close());
you can find more in the documentation here: https://mongodb.github.io/node-mongodb-native/4.1/
I'm using Mongoose to connect to mongodb.
Install mongoose npm using following command
npm install mongoose
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/database_name', function(err){
if(err){
console.log('database not connected');
}
});
var Schema = mongoose.Schema;
var userschema = new Schema ({});
var user = mongoose.model('collection_name', userschema);
we can use the queries like this
user.find({},function(err,data){
if(err){
console.log(err);
}
console.log(data);
});

Save user decoded in database

I have a aplication where the user can take some pictures and send to the database, just as simple as that.
Everytime the user login he get a token, if everything fine with the token(he doesn't need to login).
I followed this tutorial to do the jwt authentication, now i want to check on every request except(/login / register) that token and decode it to get the user info ( i am just saving the username, its unique so its fine).
So imagine i am routing to /flower?flowerName (random route) so in this route i want to create a register and save in my database some data, but before that as i said, i should enter a middleware that checks the permission.
This is my middleware:
var jwt = require('jsonwebtoken');
var jwtConfig = require('../config/jwt');
module.exports = function(req, res, next) {
console.log("entered");
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
console.log(req.headers['x-access-token']);
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token,jwtConfig.secret, function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
console.log("HEREE");
// if everything is good, save to request for use in other routes
req.decoded = decoded;
console.log(req.decoded);
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
}
my problem is, how can i get the userID for my middleware and then save it in my next route? can i pass it trough the next? like next(userID)????
How can i get the parameter then.
this is where i save the register:
var express = require('express');
var User = require('../models').User;
var Foto = require('../models').Foto;
var router = express.Router();
var jwt = require('jsonwebtoken');
var fs = require('fs');
var fsPath = require('fs-path');
module.exports = {
sendPicture: function (req, res,next) {
var bitmap = new Buffer(req.body.base64, 'base64');
var dummyDate = "25/04/14-15:54:23";
var lat = req.params.lat;
var lon = req.params.lon;
var alt = req.params.alt;
var path = __dirname + "/../public/images/" + req.params.flowerName + "/example3.png";
var fotoPath = ""
var userId = 1;
console.log(lat);
console.log(lon);
console.log(alt);
console.log(req.query.token);
fsPath.writeFile(path, bitmap, function (err) {
if (err) {
console.log(err.stack);
return err;
}
Foto.create({
image: path,
userId: userId
}).then(function () {
return res.status(200).json({ message: "foto created" });
}).catch(function(err){
console.log(err.stack);
})
});
}
}
You should be able to pass any state variables through the whole chain through res.locals, i.e.
res.locals.decoded = decoded;
next();
you can find the details on res.locals here

node js express - querying the price field

Im having trouble figuring out how to query the price. My current attempt is not working and im not sure what you have to type in the local host.
http://localhost:3000/priceSearch?
I have implemented - orderSearch.find({price:{$gt:400, $lt: 700}})
the price field in my mongodb is a number not a a string
Thank you:D
Here is my code:
priceSearch.ejs
var express = require('express');
var router = express.Router();
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/WishList';
router.get('/', function (req, res) {
var price = req.query.price;
MongoClient.connect(url, function (err, db) {
if (err) {
console.log("Unable to connect to the server", err);
} else {
console.log("Connection established...");
var orderSearch = db.collection('orders');
// find document who satisify price
orderSearch.find({price:{$gt:400, $lt: 700}}).toArray(function (err, result) {
if (err) {
res.send(err);
} else if (result.length) {
res.render('priceSearch',
{
priceSearch: result,
title: 'Product price search',
}
);
} else {
res.send("No documents found");
}
db.close();
});
}
});
});
module.exports = router;
req.query.price;
i added a stupid var to it

Some of my routes don't work in express

I'm trying to create a tic-tac-toe game and want to save the user data into a database, but my problem is that the router I want to do this with can't be reached, I get an 'Internal server error message(500)'.
Here is the index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Lab5' });
});
//check if server is online
router.get('/alive', function(req, res, next) {
res.send('alive');
});
router.post('/alive', function(req, res) {
//here I generate the next step for the game
});
//this route can't be reached
router.get('/db', function(res, req) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({}, {}, function(e, docs) {
res.send(JSON.stringify(docs));
});
});
//and this route can be reached
router.post('/db', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
var username = req.body.username;
var gameStatus = req.body.gameStatus;
try {
if(Object.keys(req.body).length !== 0 && JSON.stringify(req.body) !== JSON.stringify({})){
console.log("Data insert...");
collection.insert({
"username" : username,
"gameStatus" : gameStatus
}, function (err, docs) {
if(err) {
res.send("Error inserting data into database!");
}
});
}
} catch(err) {
console.log("Error in insert: " + err);
}
});
module.exports = router;
Here is the getDB.js:
function getDB() {
var xhttp = createRequest();
if(xhttp === null) {
alert("Ajax object not supported by your browser!");
}
else {
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
if(xhttp.responseText != null) {
var db = JSON.parse(xhttp.responseText);
console.log(db);
}
}
}
xhttp.open('GET', 'db', true);
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhttp.send();
}
}
My problem is with
router.get('/db', function() {...});
and the
router.post('/db', function() {...});
works just fine, it inserts the sent data into database.
Any help would be appreciated!
Seems that you forgot to import the mongodb bindings for express.
https://www.npmjs.com/package/express-mongo-db

Matching mail and pass in mongodb node js

So, I'm new to all this and was developing a login and registration page. I can easily save the data to the database while registering through registration page, but the problem is I don't know what to do during login page. What type of statements do I have to use to match the entered email address with the email addresses of each document in the "employee" collection, and then check if the password is correctly entered.
Here is my express file main.js:
var express = require("express");
var app = express();
var connection = require("../connection");
module.exports = function(app){
app.get('/', function(req, res){
res.render("login.html");
});
app.get('/adduser', function(req, res){
res.render("login.html");
var name = req.param('name');
var email = req.param('email');
var employeeid = req.param('employeeid');
var password = req.param('password');
var position='';
var joining_date= '';
var active= 'Y';
console.log("Name: " + name + " Email: " + email + "Employee id: " +employeeid);
connection.add(name,email,employeeid,password,position,joining_date,active);
});
//CHECKING IF MAIL AND PASSWORD MATCHES
app.get('/checkuser', function(req, res){
var email = req.param('email');
var password = req.param('password');
console.log(" Email: " + email);
connection.check(email,password);
});
And this is the connection file, connection.js:
var add=function(uname,uemail,uemployeeid,upassword,uposition,ujoining_date,uactive) {
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('employees');
//Create some users
var data = {name:uname,email:uemail,employeeid:uemployeeid,password:upassword,position:uposition,joining_date:ujoining_date,active:uactive };
/* var user2 = {name: 'modulus user', age: 22, roles: ['user']};
var user3 = {name: 'modulus super admin', age: 92, roles: ['super-admin', 'admin', 'moderator', 'user']};*/
// Insert some users
collection.insert(data, function (err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "employees" collection. The documents inserted with "_id" are:', result.length, result);
}
db.close();
});
}
});
} //NOW CHECKING IF ENTERED EMAIL AND PASS MATCHES OR EMAIL EXISTS???
var check= function(uemail,upassword)
{
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
var collection = db.collection('employees');
collection.findOne({uemail:uemail}, function(err,doc){ //I HAVE NO IDEA WHAT TO DO HERE??
if(err) throw err;
if(doc)
console.log("Found: "+uemail+", pass=");
else
console.log("Not found: "+uemail);
db.close();
});
}
});
}
module.exports.add=add;
module.exports.check=check;
EDITED: THE FIX FOR THE ABOVE PROBLEM IS PROVIDED BY GMANIC BELOW..
Here is the fix, you are trying to match on uemail but you saved it as email. You could even take it a step further and match on the password at the same time.
exports.check = function(uemail, upassword)
{
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
var collection = db.collection('employees');
collection.findOne({ email: uemail, password: upassword }, function(err, doc){
if(err) throw err;
if(doc) {
console.log("Found: " + uemail + ", pass=" + upassword);
} else {
console.log("Not found: " + uemail);
}
db.close();
});
}
});
}
There are some best practices that you should add in, but to answer your question this should work.

Categories

Resources