i'm stuck on what i know is probably a super easy issue for more experienced node.js developers to solve. i can't seem to get my returned query to display in my handlebars template.
i have my app setup like so:
app.js
var express = require('express')
, mongoose = require('mongoose')
, exphbs = require('express3-handlebars');
var uri = 'mongodb://localhost/test';
global.db = mongoose.connect(uri);
var app = express();
// configure Express
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'handlebars'); //set to handlebars to use the handlebars engine
app.engine('handlebars', exphbs({defaultLayout: 'main'})); //set to express3-handlebars to use handlebars
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use('/', express.static('public'));
app.use(app.router);
});
var api = require('./public/js/api');
app.get('/', function (req, res) {
res.render('home', {user: api.user});
});
app.listen(3000);
console.log('Listening on port 3000');
I then have my schema in a model folder and it is named userschema.js
userschema.js
var Schema = require('mongoose').Schema;
//create our user model
var userSchema = Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true},
});
// db is global
module.exports = db.model('users', userSchema);
i am then exposing the model through a js file called api.js
var model = require('../../models/userschema')
exports.modelName = function (req, res) {
res.send('my model name is ' + model.modelName);
}
exports.user = function(req, res) {
model.findOne({username: 'TestUser'}, function (err, user) {
//res.send(user);
res.render('home', {user: user.username});
console.log('USER:' + user.username);
});
}
i don't understand why i can't get this to display on my handlebars template. if i change api.user to 'ME' then i see output, if i don't i get an error. also if i go app.get('/', api.user); i see my query returned. any suggestions would be appreciated.
Well, you've already stated one possible solution, which is to bind api.user to a route such as '/':
also if i go
app.get('/', api.user);i see my query returned.
The issue is that api.user is a function -- an apparent route handler:
exports.user = function(req, res) {
model.findOne({username: 'TestUser'}, function (err, user) {
//res.send(user);
res.render('home', {user: user.username});
console.log('USER:' + user.username);
});
}
But, you seem to be trying to use it as though it's a value from your userSchema:
app.get('/', function (req, res) {
res.render('home', {user: api.user});
});
I'm guessing the error you're getting is because Handlebars is trying to execute the function as a getter. But, under this use, the 2nd argument, res, won't be an object with a render() method.