I'm trying to establish a connection between my Meteor application and my MongoDB Atlas database.
I have the following bit of JavaScript:
var MongoClient = require('mongodb').MongoClient, format = require('util').format;
MongoClient.connect('<MyMongoURL>', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
db.collection('largeTreeMap', function(err, docs) {
// Check for error
if(err) return console.log(err);
// Walk through the cursor
docs.find().each(function(err, doc) {
// Check for error
if(err) return console.err;
// Log document
console.log(doc);
})
});
}
db.close(); });
I added this to a blank JS document called test.js and upon running
node test.js
In my command line it returned the success message and data:
So now that I know the connection can be established I added the code to my Meteor project. I created a basic button and onClick the connection to MongoDB should completed.
However, instead I receive the following console error:
I understand from reading various Stack questions that this is a result of not running npm install mongodb in the project directory. However, I have tried doing this and the terminal returns:
Does any body know why the MongoDB is failing to install and preventing me from connecting to MongoDB in my application?
Any help would be much appreciated,
Many thanks,
G
You're trying to connect to the Mongo instance from the client, which is probably not what you want.
The mongodb npm package supports only Node.js, not JavaScript in the browser, as you can see from this line in its package.json
"engines": {
"node": ">=0.10.3"
},
In the case that worked, you are running it with Node.
What you probably want to do is to set the MONGO_URL environment variable to the Mongo Atlas instance, and leave the implementation of connecting / updating to Meteor itself.
Related
I have a React application that makes calls to a server.js file - these calls are requests to get data from a database with the use of queries (I'm using MSSQL).
Here is my server.js:
var express = require('express');
var app = express();
var sql = require("mssql");
var cors = require('cors');
app.use(cors())
var database = {
server: xxx,
authentication: {
type: 'default',
options: {
userName: ‘xxx’,
password: ‘xxx’,
},
},
options: {
database: ‘xxx’,
encrypt: false,
},
}
app.get(‘/gettingInfo’, function(req, res) {
sql.connect(database, function(err) {
if (err) {
console.log("ERROR HERE")
console.log(err);
}
var request = new sql.Request();
const finalRoomQuery = [query];
request.query(finalRoomQuery, function(err, recordset) {
if (err) {
console.log(err);
}
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running...');
});
Below is sample bit of code from one of my components that retrieves data from my server.js:
getData = () => {
if (this.mounted === true) {
fetch('http://localhost:5000/gettingInfo')
.then(results => results.json())
.then(results => this.setState({data: results}))
.catch(err => console.error(err));
}
}
When I run node server.js in my project directory, followed my npm start, my react application is able to retrieve data and render it appropriately.
I'm working on deploying my application. I ran npm run build to build the application, and I've deployed it to IIS. This is where I'm running into problems - if I don't have localhost:5000 running on my machine (i.e if node server.js is not entered), my application cannot query for the data needed, I get a (failed) net::ERR_CONNECTION_REFUSED. However, when I have localhost:5000 running, the application on IIS will run as expected.
My question is: how can I host this server.js file as well, and/or how can I configure this project so that I don't have to have localhost:5000 running for the application to work properly? I apologize if this is some straight forward fix or if I'm missing something very basic, this is my first experience with Web Dev.
In your server code, you are not sending response back in all cases.
app.get(‘/gettingInfo’, function(req, res) {
sql.connect(database, function(err) {
if (err) {
console.log("ERROR HERE")
console.log(err);
return res.send("Error Message");
}
var request = new sql.Request();
const finalRoomQuery = [query];
request.query(finalRoomQuery, function(err, recordset) {
if (err) {
console.log(err);
return res.send("Error Message");
}
return res.send(recordset);
});
});
});
You need to use process managers like PM2 and run your server in that console.
pm2
I have been working with nodejs google cloud functions for a while. I have been facing a weird issue where I can't connect to database servers and there is no error logged not even timeout. I am using node v14.2.0 with pg as postgres library. My nodejs code is
const { Client } = require('pg');
let connectionSetting = {
host: "host",
user: "user",
database: "db_name",
password: "password",
};
const client = new Client(connectionSetting);
console.log(connectionSetting);
client.connect(err => {
if (err) {
console.error(`Error connecting to db -> ${err}`);
}
console.log("Connection established with PgSql DB ");
});
There are no console logs or whatever.
This same code is working on other systems. The database is remote database hosted on gcp and I'm able to connect to it using tablePlus as GUI client.
Any help appreciated.
I found the issue. It has to do with the node version. I was using node current 14.2.0 so I installed node lts 12 and then everything works fine.
Thanks for all help
I am very new to MongoDB and node.
So first of all:
How can I install MongoDB using the terminal on a Mac computer
Then how can I connect MongoDB with node?
How can I create a database in MongoDB using node?
Any help is appreciated. Thank You.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:8080/mydb";
MongoClient.connect(url, function(err, db){
if(err)
{
console.log('error');
throw err;
}
else
{
console.log('success');
}
});
I tried this code but it shows an error.
This is the error I received:
You have to open the MongoDB server first.
Do this:
Go to the directory where mongo is installed: i.e.: <mongodb-install-directory>/bin
Start the server by : ./mongod --dbpath <mongo-data-directory>
I am trying to spawn a service created with pyInstaller from an electron application. I am using the following code for that:
return new Promise((reject, resolve)=>{
var exec = require('child_process').execFile;
exec(path.join(install_path, 'myService.exe'), ['--startup=auto', 'install'], function(err, data) {
if(err) {
reject(err);
return;
}
console.log(data.toString());
exec(path.join(install_path, 'myService.exe'), ['start'], function(err, data){
if(err) {
reject(err);
return;
}
resolve(data.toString());
})
});
}
Unfortunately, this throws an
Uncaught Error: spawn UNKNOWN
on a testing system, which does not have node installed and is running Windows 10 x64. On my machine it is working fine.
Does anyone have tips how I could investigate this further? I am especially curious how this error is uncaught, because the callback functions obviously contain simple error handling.
Okay, after I built in better error handling thanks to Keiths help and rebuilt the project, the testers could not reproduce the issue anymore. I am still not sure if that actually fixed the problem or if the testers pulled an old version the last time.
Anyway, this is solved.
I have one node.js application published in appfog, but when I try to access a mysql database through javascript
with ( https://github.com/felixge/node-mysql ), "node-mysql" seems that is not installed, what is the way to do this?
there is no documentation on appfog site. thanks.
the code of server app.js:
if(process.env.VCAP_SERVICES){
var env = JSON.parse(process.env.VCAP_SERVICES);
var cre = env['mysql-5.1'][0]['credentials'];
}
var Client = require('mysql').Client,
client = new Client();
client.user = cre.user;
client.password = cre.password;
client.host=cre.host;
client.port=cre.port;
client.database=cre.name;
client.connect();
client.query(
'SELECT * FROM scores ',
function selectPlayers(err, results, fields) {
if (err) {
console.log("Error: " + err.message);
throw err;
}
console.log("Number of rows: "+results.length);
console.log(results);
client.end();
});
and the error:
module.js:340
throw err;
^
Error: Cannot find module 'mysql'
at Function.Module._resolveFilename (module.js:338:15)
you should add
"mysql": "2.0.x || 2.1.x",
to the dependencies in your package.json file, and then do
npm install
You can check out Appfog's documentation here. There is a section about dependency management
Appfog have support for NPM, the standard way to install dependencies in node.
You can either do it through the console with npm install mysql or by adding mysql to your package.json file and do npm install.
The second way will automatically install all the dependencies for your app.
Source: https://docs.appfog.com/languages/node#node-dep-mgmt
Hi you just need to download and install node.js locally this will enable npm command on your machine after that go to "Services" section on your AppFog panel create you mySQL service (VCAP_SERVICES)
When you provision and bind a service to your app, AppFog creates an environment variable called VCAP_SERVICES.
This variable contains a JSON document with a list of all credentials and connection information for the bound services.
Here's an example that of the environment variable for an app that has two MySQL database services bound to it:
{"mysql-5.1":[
{
"name":"mysql-4f700",
"label":"mysql-5.1",
"plan":"free",
"tags":["mysql","mysql-5.1","relational"],
"credentials":{
"name":"d6d665aa69817406d8901cd145e05e3c6",
"hostname":"mysql-node01.us-east-1.aws.af.cm",
"host":"mysql-node01.us-east-1.aws.af.cm",
"port":3306,
"user":"uB7CoL4Hxv9Ny",
"username":"uB7CoL4Hxv9Ny",
"password":"pzAx0iaOp2yKB"
}
},
{
"name":"mysql-f1a13",
"label":"mysql-5.1",
"plan":"free",
"tags":["mysql","mysql-5.1","relational"],
"credentials":{
"name":"db777ab9da32047d99dd6cdae3aafebda",
"hostname":"mysql-node01.us-east-1.aws.af.cm",
"host":"mysql-node01.us-east-1.aws.af.cm",
"port":3306,
"user":"uJHApvZF6JBqT",
"username":"uJHApvZF6JBqT",
"password":"p146KmfkqGYmi"
}
}
]}
You can use your app's language-specific facility to call the environment variable.
In Java:
java.lang.System.getenv("VCAP_SERVICES")
In Ruby:
ENV['VCAP_SERVICES']
In Javascript:
process.env.VCAP_SERVICES
In Python:
os.getenv("VCAP_SERVICES")
In PHP:
getenv("VCAP_SERVICES")