Nodejs - Connecting to mongodb database within a js file? - javascript

So i have been looking at how to use mongodb from this tutorial: http://doduck.com/node-js-mongodb-hello-world-example/
I have installed mongodb locally within my project folder that contains my html css and js, i run npm list mongodb within the project folder and i get the mongodb version. I haven't installed it globablly, but as far as i know that is ok right?
Anyways, i tried adding the example from the tutorial to test connect to a mongodb database. I just created a function and called it as soon as my page loads:
function connectMongo(){
alert("test1");
var MongoClient = require('mongodb').MongoClient;
alert("test2");
var myCollection;
var db = MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err){
throw err;
alert("mongoerror");
}
alert("connected to the mongoDB !");
// myCollection = db.collection('test_collection');
});
}
The first test alert works, but the second test does not appear. However, the rest of the code on the page still runs, so i dont think there is a syntax error. I have no idea how exactly im meant to run this example, can anyone tell me why my function is exiting after the line
var MongoClient = require('mongodb').MongoClient;
I also have mongoose installed, even though im not quite sure if im even using it in my example here
Sorry if my question is kind of vague, i have honestly no idea what im doing here

First although Nodejs is written in Javascript, you must clearly distinguish between client and server functions. Javascript's alert() is useful to pop messages on your browser. This is isn't something Nodejs does as it is a server app.
Forget about alert("message"); You want to use console.log("message"); to view log info on the server console.
Prerequisite
Let's quickly review Client-Server web interactions:
Server is up and running
Client Requests page via browser
Page shows up on the client's browser
Step 1
The missing step for you is (1), because the server is not up and running.
This is done by typing the following on your terminal:
$ node name_of_file_here.js
If there are errors in your syntax, or missing dependencies the console will log the errors. If none appear all should be well.
Step 2
Now at this point, you still can't expect to see anything "relevant" on the browser, because your server although it has setup a MongoDB instance, is still not listening to requests from clients.
Some code needs to be added:
'use strict';
var http = require('http');
var PORT=8009;
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
var d = MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
//Create a server
var server = http.createServer(function(request, response) {
console.log("received request");
// use MongoClient to get relevant data
// var relevant_data = ...;
// response.write(relevant_data);
response.write("hey there");
response.end();
});
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});
Final Note
I am in no way a MongoDB guru, but I believe a mongodb service (server) has to be running on your system for the MongoDB client to be able to create a connection.

It sounds like you are trying to run the mongo connection javascript in the browser. The mongodb connection runs on the server via the node executable. So this is javascript code in the web app running server side, rather than javascript delivered by the web app to a browser to run client side.
Create a file test.js
function connectMongo(){
var MongoClient = require('mongodb').MongoClient;
console.log('MongoClient is',typeof MongoClient)
var myCollection;
var url = 'mongodb://127.0.0.1:27017/test';
var db = MongoClient.connect(url, function(err, db) {
if(err){
console.log("mongoerror", err);
throw err;
}
console.log("connected to the mongoDB!");
myCollection = db.collection('test_collection');
});
}
connectMongo()
Then on your system, at a command or shell prompt, run
node test.js
It should print
$ node test.js
MongoClient is function
connected to the mongoDB!
^C
Once your server is connected to the database you can pass messages from your front end javascript to the backend server code. Normally this is done via an Ajax http request, so your javascript makes additional HTTP requests in the background. The JQuery client side library provides a simple cross browser API for this. You could also use Websockets to pass message back and forth from the server via SocketIO
For the basics of a Node/Express/MongoDB app try this: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/

Related

Node.JS MySql Module - Cannot Connect to Any Database - ECONNRESET

I'm trying to use the mysql module to connect to my database. But everytime, I get the following error: read eCONNRESET There is problem. (Note, that last part is from my console log. See below.)
I don't think this is a problem with database security settings. I've been trying to connect to my new database (hosted on AWS) for the last several days with no luck. Then, just now I attempted to connect to an Azure database that has been running smoothly for a couple years. Same problem: read eCONNRESET.
By the way, if I randomly change the host string to something invalid, my code returns an error saying the host wasn't found. So that tells me it's working to some extent.
I'm very new to the coding world and need all the help I can get.
Here's my code:
console.log('starting Launch');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '....windows.net',
user : 'test',
password : 'test',
port : '1433'
})
console.log('step2')
connection.connect(function (err) {
if (!err)
console.log("conncetd");
else
console.log(err + "There is problem");
});
Copy full error message.
Check connectivity to your DB instance, use nmap (linux) or telnet (windows). If you can't reach host - check your local machine and server firewall, restrictions. If you can, go to 2.
Try to use different MySQL client, MySQL WorkBench, HeidiSQL, DBeaver.
If you can't - than something wrong with MySQL configuration. If you can, go to 3.
Copy info about: OS, node version, mysql module version.
you could try
mysql.createPool({});
instead of
mysql.createConnection({})

Using a node.js app with HTML

My goal is this: JS but server-side. My solution, the obvious, node.js. I've used node.js quiet a bit. Mainly for an application, not a web server. The only reason I need to do server-side JS is that I need to use a library that connects to the Discord API. So I have a little test .js file with my node.js in it. It just prints text if it works. Basic. What I need it to do is whenever someone goes to https://example.com/something, it runs the node.js script and if the script ends up with printing "hello", then https://example.com/something will say "hello".
I've done some research on this, I've found ways to deploy a node.js app, which I know how to do. I can't really find anything that I'm looking for though.
You can use express to run a webserver on nodejs
Install express by running "npm install express" in your project folder through command prompt
Create a app.js file with the following code
var express = require('express'); // load the express library
var app = express(); // create an instance of express
var child_process = require('child_process'); //load the child_process module
app.get("/something", function(req, res) { // Setup a router which listens to the site http://localhost/something
child_process.fork("./yourCodeFile.js"); // Launch your code file
});
app.listen(80);
Run node app.js to listen to web connections
Then you put your code into the yourCodeFile.js which has to be be in the same folder as the app.js file, even better you could just write all your code in the app.js code as long as you keep it inside the function inside app.get
You should take a look at cloud-based lambda functions and platforms like AWS Lambda, which run a script in response to an HTTP request. They are relatively new and the architecture used to support this is being called "serverless", which is a simple term, albeit a bit of a misnomer. There are various tools out there to help you build these systems, such as the similarly named Serverless framework, though you can typically still use more traditional server frameworks that you are probably more comfortable with. Either way, you are not responsible for managing any server, including starting it or stopping it.
In terms of constructing a response that you are happy with, you can of course respond with any arbitrary string you want. See the AWS example of a Node.js handler.
exports.myHandler = function(event, context, callback) {
callback(null, "Hello, world!");
}
Lambda functions can also return binary data and work well with static storage systems like Amazon S3. For example, the function can be run in response to the creation of static assets.
Your code should look like this:
const http = require('http');
const url = require('url');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
const pathName =url.parse(req.url).pathname;
if (pathName == '/something') {
res.end('Hello World\n');
} else {
res.end('Please visit /something \n');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
You should run your file with node youfile.js And when you do curl http://127.0.0.1:3000 you will see
Please visit /something
But when you do curl http://127.0.0.1:3000/something you will see
Hello World

Communication with an http-server

I have some data that I want to store locally and to be able to pull it dynamically, maybe in another session or after the browser was closed and all browser data was cleared.
I run the site with http-server CLI command and navigate to localhost to access it from the browser.
How can I send data to the server side so the server side will save the data as a file?
I tried to do an ajax post request to see if something happens in the console, but it just returned 404 and nothing came up in the console.
The docs don't mention anything about post requests: https://www.npmjs.com/package/http-server
PS: I have to run this with http-server, this is an offline project.
You will not be able to do this with http-server alone, because http-server can only serve static content and cannot be used to run any code on the server side.
You will have to write a backend yourself, possibly using a framework like Express, Hapi, Restify, Loopback etc. and serve your static files that you need with your new backend, or keep it served as you do now but then you will probably need to take CORS into account if you use different ports for your data saving/retrieving endpoints and your static content - unless you run a reverse proxy that makes it all appear on the same host name and port.
You can use the file system to save the data or you can use a database - either a standalone database like Mongo or Postgres or an embedded database like SQLite or Loki.
For examples on how to serve static content in your own backend see:
How to serve an image using nodejs
You should use express for this kind of stuff. You can easily make methods that handle certain requests.
Here is an exmaple on how to handle a get request by just sending some data
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
And you can use the fs api from node itself to write data.
var fs = require('fs')
fs.writeFile('message.txt', 'Hello Node.js', (err) => {
if (err) throw err;
console.log('It\'s saved!');
});
Note: the fs example uses arrow functions. You can find more information here

MongoDB Cloud9 Connection

So, I am wondering if there is a way to connect to the mongoDB I have setup in my Cloud9 from an html. I mean, I have already connected to the db from the terminal and everything is working like a charm but I need to do some stuff inside my script in an html document and when I try calling the function which contains this code it does nothing
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/ingesoft', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
}
db.close();
});
I have saved the same code into a "file.js" and ran it from console using node file.js and it outputs into the console log "successfully connected to the database", plus the terminal which is running mongo's connection shows me one more connection to the db. The thing is, when I try to run that code inside my script it doesn't work. Sorry for my ignorance I am new to mongo.
Any help would be much appreciated
To simplify your question, here's what's going on:
node file.js containing the code in your question is working
pasting the same code to your html file is not
So, getting to the bottom of the issue, let's ask first: what's the difference between running node file.js and putting the code in html?
The difference is that node ... is running on your Cloud9 workspace (let's call it the server machine).
Your MongoDB server is also running on that server machine
The mongodb npm package you installed is also present on the server machine
The url: mongodb://127.0.0.1:27017/ingesoft references 127.0.0.1 which is the localhost for your server
whereas with the code on your browser:
The code is being run on your customer's machine
That machine doesn't have your Mongodb server
Browser's usually don't support require
You can do requires if you bundle code and use something like webpack or browserify. Did you perhaps do that?
If you did indeed package everything, was the mongodb package that you're requiring packaged?
Can the mongodb package be run from the client side?
The url: mongodb://127.0.0.1:27017/ingesoft references 127.0.0.1 which is the localhost for your customer's machine
Basically, as you can see from the above, the two are very different.
If you want to talk to your db, a lot of people go the following route:
Make a server application that implements some form of REST API
That REST API talks to your DB
Your client code knows how to talk to the REST API and get the required data
That way, you only talk to your MongoDB using your server, and the client can talk to your server via the internet.
This is, of course, an oversimplification, but I hope this resolves your confusion.

Why isn't my node app logging to the terminal or the Chrome console?

I'm a noob when it comes to back-end with Node.
I'm running this file on an Ubuntu 14 server in the cloud. The file is being run with pm2. (ex. pm2 start newServer). The outputs from the console.log()s aren't appearing either in the terminal I've ssh'd into or in the javascript console in the browser. How can I get the file to log output into the terminal I've ssh'd into? Or am I going about this the wrong way entirely (do I need to start learning unit testing, is there some logging module I should be using, ...?)
EDIT: The pm2 logs (viewed with 'pm2 logs' or 'pm2 logs [app name]) don't contain any of the output from the console.log statements in the node script.
EDIT2: I also don't get log output anywhere when I stop the pm2 process and just run the file with node.
EDIT3: Still no output when I run the script with node on my local machine and access the page in the browser via localhost:8080.
FINAL EDIT: Figured it out. It's because my gulpfile had strip-debug in it. Being new to build systems, I didn't realize that said option removed console.logs. I found out by using node-inspector to actually look at the node code that was being run, and finding that my console.log statements had been replaced with "void 0"s.
var express = require('express'); //Require express for middleware use
const app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http); //IO is the server
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
//BASICS
app.use(express.static(__dirname + "/served")); //Serve static files
app.get('/', function(req, res){
res.sendFile('./index.html');
});
io.on('connection', function(socket){
// socket.on('chat message', function(msg){
// io.emit('chat message', msg);
// });
console.log("A user connected: ", socket.id);
});
http.listen(8080, function(){
console.log('listening on *:8080');
});
console.log('test')
// MONGODB
var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server.");
db.close();
});
I'm not an expert on pm2, but from a quick glance it's designed for production use, and won't log anything to the terminal.
Looking at the page
https://github.com/Unitech/pm2
There is a section on Log facilities which tells you how to look at the logs, with a command like this
pm2 logs APP-NAME # Display APP-NAME logs
Otherwise if you really just want to see what it is doing, just run your code with node, eg
node myprogram.js
When using the pm2 module the logs are saved per separate node. In order to view them you can issue the command pm2 logs to view the logs for each node.

Categories

Resources