我是Nodejs和JavaScript的新手。我已經開始了一個使用快遞發電機的項目,並且已經安裝了貓鼬皮卡。Nodejs變量聲明
的路線/ index.js文件,我有這樣的代碼
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
var toSchema = mongoose.Schema({
name: String,
state : Boolean
});
var listing = mongoose.model('todoSchema', toSchema)
});
/* GET home page. */
router.get('/', function(req, res) {
var silence = new listing({ name: 'Silence', state:true })
console.log(silence.name) // 'Silence'
res.render('index', { title: silence.name });
});
module.exports = router;
但是當我啓動服務器,我得到錯誤說
listing is not defined
ReferenceError: listing is not defined
at module.exports (D:\xampp\htdocs\nodeproject\myapp\routes\index.js:18:20)
at Layer.handle [as handle_request]
D:\xampp\htdocs\nodeproject\myapp\node_modules\express\lib\router\layer.js:82:5)
at next (D:\xampp\htdocs\nodeproject\myapp\node_modules\express\lib\router\route.js:100:13)
at Route.dispatch (D:\xampp\htdocs\nodeproject\myapp\node_modules\express\lib\router\route.js:81:3)
at Layer.handle [as handle_request] (D:\xampp\htdocs\nodeproject\myapp\node_modules\express\lib\router\layer.js:82:5)
at D:\xampp\htdocs\nodeproject\myapp\node_modules\express\lib\router\index.js:235:24
at Function.proto.process_params (D:\xampp\htdocs\nodeproject\myapp\node_modules\express\lib\router\index.js:313:12)
at D:\xampp\htdocs\nodeproject\myapp\node_modules\express\lib\router\index.js:229:12
at Function.match_layer (D:\xampp\htdocs\nodeproject\myapp\node_modules\express\lib\router\index.js:296:3)
at next (D:\xampp\htdocs\nodeproject\myapp\node_modules\express\lib\router\index.js:190:10)
你能告訴我什麼我做錯了,變量聲明如何工作?
http://stackoverflow.com/questions/18259725/whats-the-proper-way-to-handle-mongoose-connections-with-express-js – BatScream