我正在尝试制作一个简单的博客应用。我可以让应用程序在第一次尝试时向DB提交内容,但如果您再次尝试节点崩溃。我无法弄清楚原因。
post.js:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
PostSchema = new Schema({title: {type: String, "default": ''},
content: {type: String, "default": ''}});
Post = mongoose.model('posts', PostSchema);
module.exports.Post = Post;
module.exports.PostSchema = PostSchema;
db-conn.js:
var mongoose = require('mongoose'),
Post = require('./post').Post;
var createPost = function(newTitle, newContent){
mongoose.connection.once('open', function(){
var p = new Post({ title: newTitle,
content: newContent });
p.save(function(err){
if (err) throw err;
});
});
mongoose.connect('mongodb://user:pass@(myIP):27017/blog', function(err){
if (err) throw err;
});
mongoose.disconnect();
};
module.exports.createPost = createPost;
然后在我的server.js文件中,我只是从页面接收标题和内容并将它们传递给db-conn.js。就像我说的,第一次运行createPost时它运行成功。第二次尝试崩溃。有什么想法吗?
答案 0 :(得分:1)
您的代码存在一些问题,因此我只是将其复制并对其进行了评论。
var createPost = function(newTitle, newContent){
mongoose.connection.once('open', function(){
var p = new Post({ title: newTitle,
content: newContent });
p.save(function(err){
if (err) throw err;
});
});
// This should only be happening once, usually during application setup.
mongoose.connect('mongodb://user:pass@(myIP):27017/blog', function(err){
if (err) throw err;
});
// You almost never need to call this yourself, but even if this call was
// legit it should not be called immediately after `connect`. You haven't
// even waited for the connection to be open before you've disconnected it.
mongoose.disconnect();
};
将回调函数传递给mongoose.connect
的原因是因为mongoose.connect
是异步的。这意味着您的mongoose.connect
在调用它之后会立即返回 ,并且您的程序会转到下一个调用。与此同时,mongoose现在忙于连接数据库,通常需要几秒钟。当它完成连接时,它必须调用你传入的回调。这就是你传递将在mongoose完成后执行的逻辑的方式。
基本上你立即调用mongoose.connect
然后调用mongoose.disconnect
。如果您在完成连接之前致电mongoose.connect
,我甚至不确定您的disconnect
回叫是否会被调用。
另外,我应该指出:
mongoose.connect('mongodb://user:pass@(myIP):27017/blog', function (err) {
if (err) console.error(err);
// connection is now open.
});
与:
完全相同mongoose.connection.once('open', function () {
// connection is now open.
});
mongoose.connect('mongodb://user:pass@(myIP):27017/blog');
理想情况下,在Web应用程序中,您将在应用程序启动时连接到数据库。
var http = require('http');
var mongoose = require('mongoose');
mongoose.connection.once('open', function () {
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
}):
mongoose.connect(connectionString);
答案 1 :(得分:0)
你应该只是打电话
mongoose.connection.once(...
一次,而不是每次都收到一篇http帖子(我通常在主app.js文件中调用它,并在成功返回后启动我的node / express app)。在您的createpost功能中,您应该只有
var p = new Post({ title: newTitle,
content: newContent });
p.save(function(err){
if (err) throw err;
});