Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Mongoose不能发布数据两次_Javascript_Node.js_Mongodb_Mongoose - Fatal编程技术网

Javascript Mongoose不能发布数据两次

Javascript Mongoose不能发布数据两次,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我正在尝试制作一个简单的博客应用程序。我可以让应用程序在第一次尝试时将内容提交到DB,但如果第二次尝试,则节点会崩溃。我不明白为什么 post.js: var mongoose = require('mongoose'), Schema = mongoose.Schema; PostSchema = new Schema({title: {type: String, "default": ''}, content: {type: Str

我正在尝试制作一个简单的博客应用程序。我可以让应用程序在第一次尝试时将内容提交到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时,它会成功运行。第二次尝试失败。有什么想法吗?

你只需要打电话

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

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

你的代码有几处错误,所以我只是复制了它并对其进行了注释

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。连接
,然后
mongoose。几乎立即断开连接。我甚至不确定您对
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);

我用了mongoose.connection.one('open')这个词,因为我在一个不同的SO威胁中看到了它,主题大致相同。我将初始连接移动到初始服务器创建,并完全删除了断开连接。它现在似乎正在按预期工作。谢谢。很好。我很高兴你让它工作了。如果你想用猫鼬做一个更简单的设置,这样你就不必再去想那些东西了,那么看看我的模块吧。只要浏览一下自述文件,您就会立即看到它在多大程度上简化了开始使用猫鼬的过程。