在这里,我有一个服务器和一个进行 ajax 调用的 html 文件。我想在发布时将用户名和密码放入数据库中。当我第一次加载客户端并发送信息时,它成功进入数据库,但如果我发送另一批信息,我会收到错误:以下是错误:
Connected successfully to server Inserted 3 documents into the collection the options [servers] is not supported the options [caseTranslate] is not supported the options [dbName] is not supported Connected successfully to server Inserted 3 documents into the collection
在我重新启动服务器之前,我的数据库将不再填充。有人可以指出我正确的方向吗?这可能是我在 .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>
服务器.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");
最佳答案
以防万一其他人发生在这篇文章中,我遇到了类似的错误,并且能够通过将客户端创建行移动到我从数据库模块导出的异步函数中来解决它:
'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;
改为:'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;
其他人可能比我更了解,但我认为这与使用未正确关闭的旧客户端而不是新客户端有关。
关于node.js - Mongodb:不支持选项 [...],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59941067/