Can Nodejs retrieve data from Meteor mini mongo? - javascript

I'm trying to use Nodejs to get data from Meteorjs mini mongo database. Here is my code:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://127.0.0.1:3001/meteor', function(err, db) {
if(err) throw err;
console.log("Connected to Database");
var test = db.collection("apps");
test.insert({"_id":"selfDefinedID"}, function(err,docs){
console.log("docs inserted");
console.log(docs);
});
test.find({"_id":"selfDefinedID"}).toArray(function(err,docs){
console.log("docs founded");
console.log(docs);
});
});
Insert data works fine. But, I can't retrieve data from meteor mini mongo database. And I got an error:
{ [MongoError: Connection Closed By Application] name: 'MongoError' }
Is it possible to retrieve Meteor mini mongo data using Nodejs? If possible, how?

The database meteor uses is a normal mongo database. You can connect to it like any other mongo db. If you are still in development mode, then the database runs at mongodb://localhost:3001/meteor, otherwise, in a bundled app, it's just the db you specified yourself using MONGO_URL.

On a windows machine, I created a new, blank, meteor project, and started it up. I then created a test script, npm installed the mongodb library, and ran your script and it worked fine. First run I get "docs inserted" and "docs founded", on subsequent runs obviously the insert is failing, but the find still works.
So two questions, first is this the same script your getting the error with? And two, if you create a blank meteor project and try it do you get the same error?

Related

Legacy Meteor application not fetching documents on server

I'm supporting a legacy Meteor 1.2.1 application using MongoDB Atlas and without any apparent code changes, it is suddenly not showing any documents - The code has not been changed for at least 5 months.
Looking in the DB, the documents are there, but on the server side, the find().fetch() calls are all returning 0 documents:
var documents = Articles.find().fetch();
console.log(`++ Found: ${documents.length} articles`);
logs:
++ Found: 0 articles
Interestingly, if I grab hold of the raw DB connection that Meteor is using and do a query myself, the data is found:
var getDocumentCounts = function (collectionName) {
var Future = Npm.require('fibers/future'), future = new Future();
var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
db.collection(collectionName).count(
function(error, results) {
if (error) throw new Meteor.Error(500, "failed");
future.return(results);
}
);
return future.wait();
}
var result = getDocumentCounts('articles');
console.log(`articles: ${result}`);
logs:
articles: 259
The application is using some NPM packages, but is using an npm-shrinkwrap.json (legacy again) to ensure the versions of them are not accidentally upgraded during a restart/rebuild.
Node is from the Jurassic era # v0.10.41
I can't think why the application would suddenly develop this problem. Looking for a simple solution rather than the longwinded "upgrade everything"
Also interestingly, if I connect to my local dev mongo db, everything works fine. The MongDB Atlas is using shards whereas the local mongo is not, but it has had those shards for many many months.
My best opinion is that the problem is being caused by the fact that the mongo driver used by your Meteor version is no longer compatible with the mongo version running in Atlas. Check the Atlas MongoDB version, if possible.

communicate between apps over network

I'm trying to build an app that would be able query a database over wifi, I think I'd make two different apps. One running the database, receiving queries, and sending data to the other app, (on another device) querying the database. My problem is I can't find anything that could help me send simple SQL or JSON queries over wifi in an electron app.
If someone could just point me in the right direction or if someone has done this sort of thing before that would be great.
Hey #coolWinter you would need a database driver in nodejs , using this driver package you may use it's expose method and query database and process the ResultSet.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Electron is basically a nodeJs using Chrome V8 Engine wrapped for desktop application - so there should not be any problem using any driver in electron application
https://www.npmjs.com/package/mysql

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({})

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.

Nodejs - Connecting to mongodb database within a js file?

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/

Categories

Resources