Mongoose .save函数似乎没有在node.js脚本中调用

我是一个初学node.js和mongoose和全栈web开发的总体。 我一直在殴打我的头来build立一个数据库,并与我的服务器进行通信,并不能完全正常工作。 我一直松散地遵循这个教程: 使用Mongoose轻松开发Node.js和MongoDB应用程序

无论如何,我的文件目前组织得相当简单。 我的server.js与包含我的“testSchema.js”文件的“models”文件夹位于同一目录中。

我有一个脚本,可以通过按下我的server.js文件中的button来调用。

var mongoose = require('mongoose'); var mongoURL = "mongodb://username:password@localhost:27017/test"; mongoose.connect(mongoURL); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log("We have connected"); var Item = require("./models/testSchema"); var newItem = Item({ name: 'Peter', score: 5 }); newItem.save(function(err) { if (err) throw err; console.log("Item Created"); }); }); mongoose.connection.close(); 

这应该将示例文档添加到我的模型中。 最后,testSchema.js:

 var Schema = mongoose.Schema; var ItemSchema = new mongoose.Schema({ name: { type: String, index: true }, score : Number }); var Item = mongoose.model('Item', ItemSchema); module.exports = Item; 

所以,当我运行这个脚本的时候,我得到了“我们已经连接!”的消息,但是没有消息“Item created”,也没有调用.save函数之后的任何错误日志。 这似乎只是越过,但我不知道如何mongoose和node.js在这种情况下行为。 .save甚至被叫了?

另外:我的mongoDB数据库托pipe在Openshift,但我已经端口转发到本地主机,它看起来像工作正常。 每当我调用脚本,我都会收到“处理27017连接”的消息。

任何帮助将不胜感激!

**编辑**

我不能评论,所以我只是编辑我的post。

扎克里·雅可比(Zachary Jacobi)和罗伯特·克莱普(Robert 非常感谢,我不知道节点是asynchronous的。

节点在I / O上是asynchronous的,所以事情不一定按照它们出现在代码中的顺序发生。

在这里,数据库连接被打开,节点移动到下一个语句,而不用等待callback中的其余部分完成。 所以mongoose.connection.close(); 实际上是在newItem.save(function(err) {...之前执行的。

要解决这个问题,请尝试:

 var mongoose = require('mongoose'); var mongoURL = "mongodb://username:password@localhost:27017/test"; mongoose.connect(mongoURL); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log("We have connected"); var Item = require("./models/testSchema"); var newItem = Item({ name: 'Peter', score: 5 }); newItem.save(function(err) { if (err) throw err; console.log("Item Created"); mongoose.connection.close(); }); });