Reputation: 258
Here I have a server and an html file making an ajax call. I want to put the username and password inside the database when posted. When I FIRST load up the client and send the information, it goes into the database successfully, but if i send another batch of information I get an ERROR: the following is the error:
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
And My database will no longer populate until i restart the server. Can someone please point me in the right direction? could it be the way I've structured the client connect inside the .on POST event?
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>
SERVER.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");
Upvotes: 8
Views: 9320
Reputation: 61
Just in case anyone else happens upon this post, I was having a similar error and was able to solve it by moving the client creation line into the async function I was exporting from my database module:
'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;
was changed to this:
'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;
Someone else might know better than me, but I assume it has something to do with using an old client that wasn't closed properly instead of a new one.
Upvotes: 6
Reputation: 315
As discussed in comments above, the solution to this problem was to follow Mongodb best practices and not close the client's connection each time data was to be written to the database.
Upvotes: 3