我被困在我所知道的可能是更有經驗的node.js開發人員解決的一個超級簡單問題。我似乎無法讓我返回的查詢顯示在我的把手模板中。node.js - express3-handlebars和mongoose
我有我的應用程序的設置,如下所示:
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');
然後我有我的架構模型中的文件夾並將其命名爲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);
我然後通過名爲api.js的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);
});
}
我不明白爲什麼我無法將它顯示在我的把手模板上。如果我將api.user更改爲'我',那麼我會看到輸出,如果我沒有收到錯誤。如果我去app.get('/',api.user);我看到我的查詢返回。任何建議,將不勝感激。