Mongodb:不支持选项 [...]

chr*_*ree 5 mongodb node.js

在这里,我有一个服务器和一个 html 文件进行 ajax 调用。我想在发布时将用户名和密码放在数据库中。当我第一次加载客户端并发送信息时,它成功进入数据库,但如果我发送另一批信息,我会收到一个错误:以下是错误:

成功连接到服务器 将 3 个文档插入到集合中 不支持选项 [servers] 不支持选项 [caseTranslate] 不支持选项 [dbName] 成功连接到服务器 将 3 个文档插入到集合中

在我重新启动服务器之前,我的数据库将不再填充。有人可以指出我正确的方向吗?这可能是我在 .on POST 事件中构建客户端连接的方式吗?

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>
            Little structure
        </title>
    </head>
    <body>

        <div id="demo">
            <h1>Click ere</h1>
            <button type="button" onclick="loadDoc()">Submit</button></br>
            <input id = "userName"></input> </br>
            <input id = "userPW" type = "password"></input></br>
        </div>

        <script>



            function loadDoc() {
                    //get user value
                    var userName = document.getElementById("userName").value;
                    var userPW = document.getElementById("userPW").value;

                    //initiate POST request
                    var xhr = new XMLHttpRequest();

                    xhr.open("POST", 'server.js', false);

                    //Send the proper header information along with the request
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

                    xhr.onreadystatechange = function() { // Call a function when the state changes.
                        if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
                            // Request finished. Do processing here.
                        }
                    }
                    xhr.send("userName=" + userName + "&userPW=" + userPW);
                }
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

服务器.js

var http = require('http');
var fs = require('fs');
var qs = require('querystring');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert').strict;

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Create a new MongoClient
const client = new MongoClient(url);

    var server = http.createServer(function (req, res) {
        client.connect(function(err) {
            assert.equal(null, err);
            console.log("Connected successfully to server");

            const db = client.db(dbName);

            if(req.method == "GET")
            {
                if(req.url === '/'){ 
                    fs.readFile('home.html', function(err, data) {
                        res.writeHead(200, {'Content-Type': 'text/html'});
                        res.write(data);
                        res.end();
                    });
                }
            }
            else if (req.method == 'POST') {
                var body = '';

                req.on('data', function (data){
                    body += data;
                })

                req.on('end', () => {
                    var postData = qs.parse(body);

                    // Use connect method to connect to the Server


                        // Get the documents collection
                        const collection = db.collection('doc');
                        // Insert some documents
                        collection.insertOne(postData, function(err, result) {
                            console.log(postData);
                            client.close();
                        });

                    res.end();
                })
            }
        });
    });


    server.listen(3000);
    console.log("listening on 3000");
Run Code Online (Sandbox Code Playgroud)

小智 6

以防万一其他人看到这篇文章,我遇到了类似的错误,并且能够通过将客户端创建行移动到我从数据库模块导出的异步函数中来解决它:

'use strict';
require('dotenv').config();

const MongoClient = require('mongodb').MongoClient;
const uri = process.env.MONGO_URI;

//  Was creating a new MongoClient here
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

async function main(callback) {
 
  try {
    await client.connect();
    await callback(client);
  } catch (err) {
    throw new Error('Unable to Connect to Database')
  } finally {
    await client.close();
  };

}

module.exports = main;
Run Code Online (Sandbox Code Playgroud)

被改为这样:

'use strict';
require('dotenv').config();

const MongoClient = require('mongodb').MongoClient;
const uri = process.env.MONGO_URI;

async function main(callback) {

  //  Now creating a new MongoClient here and everything works great
  const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
  
  try {
    await client.connect();
    await callback(client);
  } catch (err) {
    throw new Error('Unable to Connect to Database')
  } finally {
    await client.close();
  };

}

module.exports = main;
Run Code Online (Sandbox Code Playgroud)

其他人可能比我更了解,但我认为这与使用未正确关闭的旧客户端而不是新客户端有关。


Bri*_*tar 3

正如上面评论中所讨论的,这个问题的解决方案是遵循 Mongodb 最佳实践,并且每次将数据写入数据库时​​不要关闭客户端连接。