我似乎无法找到一种方法来导出我从数据库中获取的用户数据。当我在另一个文件中需要它时,我得到未定义的值或空对象。请帮助我想要的是导出用户信息,以便我可以在另一个文件中使用它。
我的auth.js文件:
// 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();
});
});
}
});
});
我的app.js文件:
// 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();
}
});
});
提前谢谢!