Unable to add array data to MongoDB collection - javascript

I have 2 URLs, one points to a different connection string and the other to local MongoDB instance. While I establish the connection to MongoDB using MongoClient with url1 and fetch the required data from a DB/collection and lastly store it in an array.
Now I want to insert this array to a localhost MongoDB collection and on doing so I get MongoError: Topology is closed, please connect error.
app.js
var url1="someurl but not localhost";
var url2="mongodb://localhost:27017/";
router.get('/route1', function(req, res)
{
MongoClient.connect(url1,{ useUnifiedTopology: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("customer");
dbo.collection("customer_report").find({}).toArray(function(err, result) {
if (err!=null){
console.log("Connection Failed!!"+err)
}
var customerArray =[];
for(i=0;i<result.length;i++){
backupArray.push({
a: result[i].a,
b: result[i].b,
c: result[i].c,
d: result[i].d,
});
}
console.log(customerArray);
res.json({content:customerArray});
db.close();
MongoClient.connect(url2,{ useUnifiedTopology: true }, function(err, db1) {
//Trying to establish another mongodb connection wuth new url
if (err) throw err;
var dbo = db.db("localdb");
dbo.collection("localcollection").insertMany(customerArray, function(err, res) {
if (err) throw err;
console.log("Number of documents inserted: " + res.insertedCount);
db1.close();
});
});
});
});
});
And if I don't close db.close(); then the array data gets appended to first MongoDB collection and not the local MongoDB. Looking for a solution to handle two MongoClient at the same time or a way to insert the customerArray to local MongoDB collection.
Is there a workaround where I can add the array elements to my local MongoDB collection?

In your second mongo connect block I think you want
var dbo = db.db("localdb");
to be
var dbo = db1.db("localdb");

Have you made sure those credentials work in console commands? And have you made sure the last connection through the console is closed before trying to use them in the script?

Related

Error: Connection lost: The server closed the connection. Nodejs / mysql

I am having a few issues with one route that I am looking at...
app.get('/newusersvariables', function(req, res) {
const sessionid = req.session.id;
//let newuser = mysql.createConnection(mysqlconfig);
let connection = mysql.createConnection(mysqlconfig);
connection.connect(function(err) {
if (err) throw err;
connection.query("SELECT * FROM user_idpdetails WHERE sessionid = ?", [sessionid], function (err, result, fields) {
if (err) throw err;
console.log(result);
connection.end();
});
});
I have tried moving around the connection.end but to no avail. In some situations, I get connection lost, as if it is ignoring the connection end. And if I move it to other places then I am getting
'Error: Cannot enqueue Query after invoking quit.'
It is most likely something simple that I am overlooking as I am new to node.

How do I send data from MySQL database connected to a Node.js server so that I can use it for client side JavaScript?

To preface, I'm completely new to NodeJs and MySQL.
I have a website running on Node with express like this
var express = require('express');
var app = express();
var path = require("path");
var mysql = require("mysql");
app.use(express.static('Script'));
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "blocks"
});
con.connect(function(err){
if(err) throw err;
console.log("connected!");
con.query("SELECT * FROM blockchain", function(err, result, fields){
if(err) throw err;
console.log(result);
});
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
It's connected to the server successfully, and can print out the server values on my command prompt.
Is there a way to send this data to my website such that I can use the values for client side scripting? For example, I want a create a new <p> element in my index.html file to represent every entry in the database, and thus alter my websites displayed information.
So if the database was empty, my website would look empty. If the database had three entries, my website would have 3 <p> elements that corresponded to the inputs of the three entries.
To easy. At first we open the db connections:
con.connect(function(err){
if(err) throw err;
console.log("connected!");
Then if the connection is set up, we can start answering requests:
app.get("/", (req, res) => {
Now when a request comes in, we get the latest data from the db:
con.query("SELECT * FROM blockchain", function(err, result, fields){
if(err) return res.end("sth went wrong :(");
res.end(result);
});
});
});
Now you only need to transfer the data into html, for that i would recommend using a template engine.
When you query data from a database, it is an asyncronous operation. In other words, it takes time before you have all the data.
So in your case it sounds best to use a promise:
var mysql = require('promise-mysql');
mysql.createConnection({
host: 'localhost',
user: 'sauron',
password: 'theonetruering',
database: 'mordor'
}).then(function(conn){
var result = conn.query('select `name` from hobbits');
conn.end();
return result;
}).then(function(rows){
for (var i in rows){
document.write("<p>name[i]</p>");
}
});
The funtion after .then executes when your query has finished. Now you can sort you query with a for loop.
mysql-promise: https://www.npmjs.com/package/promise-mysql
HTML DOM write: https://www.w3schools.com/jsref/met_doc_write.asp

How to connect to mongodb and How to print list of all collection from a dabase in mongodb using node.js program

Hi I tried to connect to mongodb and print all collection from a dabase in mongodb using node.js program but i am getting error. Code I tried is as below.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://ipaddressofmywebsite:27017/databasename", function(err, db) {
if(!err) {
console.log("We are connected");
var m = new MongoClient();
var db = m.selectDB("databasename");
var list= db.getCollectionNames();
console.log(list);
}
});
**I get the following error**
throw err
^
TypeError: m.selectDB is not a function
When I tried the below code as suggested in this page also i get error.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://websiteipaddress/databasename",
function(err, db) { // The db is passed in here.
if(!err) {
console.log("We are connected");
var list= db.getCollectionNames();
console.log(list);
}
});
**Error i get is**
throw err
^
TypeError: db.getCollectionNames is not a function
Kindly help me to fix this error
You don't need to select a database. You already did that in the connection string: mongodb://ipaddressofmywebsite:27017/databasename. This should work:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://ipaddressofmywebsite:27017/databasename",
function(err, db) { // The db is passed in here.
if(!err) {
console.log("We are connected");
db.collectionNames(function(err, names) {
console.log(names);
});
}
});
Here is the docs for MongoClient - About getting the collection names

Node.js + MongoDB methods insertOne or insert issue

I have this issue with node.js and mongodb.
I followed the example from mongodb.github.io, '
the code is:
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
// Connection url
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to server
MongoClient.connect(url, function(err, db){
assert.equal(null, err);
console.log('Connected to server');
// Insert a single document
db.collection('test').insertOne({a:1}, function(err, r){
assert.equal(null, err);
assert.equal(1, r.insertedCount);
});
});
in my console i get the following error:
Object #Collection has no method 'insertOne'.
Any ideas why?

How can i pipe mysql data to a browser window instead of the console in Nodejs?

Hi I am currently trying to output mysql data to a browser window instead of the console, and I have not a clue on how to do this in Node, which I am quite new to.
Here is the mysql.js file:
'
var mysql = require ("mysql");
var connection = mysql.createConnection({
host:"localhost",
user: "root",
});
connection.connect(function (err) {console.log( "Successfully Connected.");
if (err) throw err;
});
var query = connection.query("SELECT * FROM myTable", function (err, result, fields){
if (err) throw err;
console.log('result:', result);
});
connection.end();'
You need to create a server which you can connect to and receive data from with a browser. The most convenient and by far the simplest way to do this is HTTP. You can read about HTTP servers in node.js here. The fist code snippet on that page demonstrates a HTTP server with one handler function, which is all you need to achieve your goal.
An (untested) example for convenience:
// Dependencies
var mysql = require("mysql"),
http = require("http");
// This holds our query results
var results;
// Connect to database
var connection = mysql.createConnection({
host: "localhost",
user: "root"
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected to database");
});
connection.query("SELECT * FROM myTable", function(err, rows, fields) {
if (err) throw err;
results = rows;
connection.end(); // Disconnect from database
});
// Function to handle browser's requests
function requestHandler(req, res) {
res.end(JSON.stringify(results)); // Respond to request with a string
}
// Create a server
var server = http.createServer(requestHandler);
// That magic number 8080 over here is the port our server listens to.
// You can access this webpage by visiting address http://localhost:8080
server.listen(8080, function() {
console.log("Server online");
});

Categories

Resources