从Node js将集合添加到Mongo数据库时出错

时间:2020-06-09 22:22:49

标签: javascript node.js mongodb

我正在尝试使用Node从server.js文件将集合添加到mongo数据库中。以前这似乎可行,但现在却让我出错。这是代码:

          if (thread_found == false){ // thread does not already exist
                console.log("Thread?"); 
                console.log(thread_found); 

                // --------------- this code throws an error ---------------------
                db.createCollection(req.body.thread, function(err, res){
                    if (err) throw err; 
                    console.log("Collection has been created!"); 
                }); 

                // ---------------- this code throws an error -------------------
                // db.createCollection(req.body.thread, function(err, result){
                //  console.log("Before the error that we are getting"); 
                //  if (err){
                //      console.log(err); 
                //      throw err; 
                //  }
                //  console.log("Collection is created"); 
                //  // db.close(); 
                // }); 

                collection_names.push(req.body.thread); 

                var thread_content = {user: req.body.username, text: req.body.comment }; 

                db.collection(req.body.thread).insertOne(thread_content, function(err, res){
                    console.log("putting comment into created thread!!!"); 
                    console.log(req.body.comment); 
                    console.log("--------------------------------------------");

                    if (err) throw err;
                    console.log("1 document inserted");
                    // client.close(); 
                    // console.log("Here we are"); 
                    // console.log("Last stop before error message?"); 
                });

                database.close(); 

                // fs.writeFileSync('threads.json', JSON.stringify(thread_content)); 


            }

它引发的特定错误是:“ MongoError:服务器群集无可用连接”。

0 个答案:

没有答案