【问题标题】:Mongoose Cannot Post Data TwiceMongoose 不能两次发布数据
【发布时间】:2014-01-29 13:14:33
【问题描述】:

我正在尝试制作一个简单的博客应用程序。我可以让应用程序在第一次尝试时将内容提交到数据库,但如果您第二次尝试节点崩溃。我不知道为什么。

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 时它会成功运行。第二次尝试崩溃。有什么想法吗?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案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.connect 然后mongoose.disconnect。如果您在连接完成之前调用disconnect,我什至不确定您对mongoose.connect 的回调是否会被调用。

    另外,我应该指出这一点:

    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);
    

    【讨论】:

    • 我使用了那个 mongoose.connection.once('open') 东西,因为我在不同的 SO 威胁中看到了它,主题大致相同。我将初始连接移至初始服务器创建,并完全删除了断开连接。它现在似乎按预期工作。谢谢。
    • 很好,我很高兴你能成功。如果您正在寻找更简单的 mongoose 设置,因此您不必再考虑这些东西,请查看我的 mongoose-simpledb 模块。只需看一下自述文件,您就会立即看到它在多大程度上简化了 mongoose 的入门。
    【解决方案2】:

    你应该只打电话

    mongoose.connection.once(...
    

    一次,而不是每次收到 http 帖子(我通常在主 app.js 文件中调用它,并让它在成功返回后启动我的 node/express 应用程序)。在您的 createpost 函数中,您应该只有

      var p = new Post({ title: newTitle,
                           content: newContent });
        p.save(function(err){
          if (err) throw err;
        });  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2019-10-09
      • 2015-03-30
      • 1970-01-01
      • 2016-02-10
      相关资源
      最近更新 更多