Reputation: 2741
I am trying to export the mongoose variable to another JS file but I can't get it to work.
I want to export the user variable which is a mongoose model. If I include the mongoose things directly inte results.js then it will work.
Error: TypeError: app.user is not a constructor at projects\api\js\results.js:12:23
app.js
var express = require("express");
var session = module.exports = require('express-session');
var bodyParser = module.exports = require('body-parser');
//MongoDB
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/time_report");
var userSchema = new mongoose.Schema({
name: String,
password: String
});
var user = mongoose.model("user", userSchema);
var app = module.exports = express();
exports.user = user; //This variable is not reachable
results.js
var app = require("./app.js");
function showDate() {
app.get("/results", function(req, res) {
//Get login info
var uName = req.query.username;
var pw = req.query.password;
var newUser = app.user({ //Fail here
name: uName,
password: pw
});
console.log(newUser.name);
// Check to match with database
user.findOne({ name: newUser.name, password: newUser.password }, function(err, user) {
if (err) return handleError(err);
if (user) {
console.log("Logged in");
//console.log('This is great! %s %s', user.name, user.password);
res.render("results", { data: newUser });
} else {
res.send("Failed to login");
}
});
});
}
Upvotes: 0
Views: 3252
Reputation: 982
In app.js
, change this:
//...
var app = module.exports = express();
exports.user = user; //This variable is not reachable
with this:
//...
module.exports = {
app: express(),
user
}
Then, in result.js
change this line:
var app = require("./app.js"); // <----- NO
with this other one:
var {app, user} = require("./app.js"); // <----- YES
And of course, in result.js you want instantiate a new user (so don't forget the new keyword):
var newUser = new user ({ //No longer fails here
name: uName,
password: pw
});
Upvotes: 2