我正在尝试学习 node 和 mongo 以构建一个简单的 web 应用程序/自学更多关于 web 应用程序的知识。但是,当我调用 Model.save() 时,延续函数似乎永远不会执行,并且数据也没有保存。
这是我到目前为止所拥有的:
/* app.js */
var express = require('express')
, app = express()
, routes = require('./routes')
, http = require('http')
, path = require('path')
, mongoose = require('mongoose')
, db
, Track
, models = require('./models.js');
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('secretstuff'));
app.use(express.session());
app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
});
models.defineModels(mongoose, function(){
app.Track = Track = mongoose.model('Track');
db = mongoose.createConnection('localhost','nextrak')
});
app.get('/', routes.index);
app.get('/dbTest', function(req, res){
console.log("Here goes...");
var t = new Track({
name: "TestTrack",
artist: "Artist",
tags: ["test"],
next: ["track1","track2"]
});
console.log("Test Track:");
console.log(t);
t.save(function(){
if(err)
console.log("Error! Couldn't complete dbTest successfully.");
else
console.log("Aw yiss, got dbTest working");
})
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
/*models.js*/
function defineModels(mongoose, cont){
var Schema = mongoose.Schema;
Track = new Schema({
'name': { type: String, index: true },
'artist': String,
'tags': [String],
'next': [String],
});
mongoose.model('Track', Track);
cont();
}
exports.defineModels = defineModels;
没有抛出错误,mongo 日志表明当我启动我的应用程序时启动了 5 个新连接。不会出现新的日志([clientcursormon] 日志除外)。当我在 Chrome 中加载 /dbTest 时,该应用程序会打印出以下内容:
开始...
Test Track:
{ name: 'TestTrack',
artist: 'Basik',
_id: 5031606aa11cf95815000001,
next: [ 'track1', 'track2' ],
tags: [ 'test' ] }
Mongo 似乎配置正确。当我让节点运行 Mongoose 引导您完成的简单“入门”脚本时,一切正常。
谁能指出我做错了什么?