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>
Related
I am a beginner to node.js and MongoDB. I am trying to setup a basic project like so.
In my project dir I run node init, accept the default values and then run npm install --save mongodb. In my index.js I have the following code:
// Import the mongodb module
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:3333/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
Now when I run node index.js I get the following error:
failed to connect to server [localhost:3333] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:3333]
I have tried changing the port number but still get the same error. What am I doing wrong here?
By default the MongoDB server is running on port 27017. You need to change the connection string to mongodb://localhost:27017/mydb.
First you need to install MongoDB if you don't already have it installed. Visit MongoDB site to download.
Follow the instructions there on how to start it up and running, after that try running your app again.
Also by default MongoDB runs on port 27017 so your url should point to localhost:27017.
// Import the mongodb module
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
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.
I've written a code that should retrieve data from database with nodejs and mysql but it's not working.
It says the I didn't installed the mysql module but I did, using npm install:
The proof that I installed the mysql module successfully:
Is my code ok ? Keep in mind that I'm completely new to node.js.
var http = require('http');
http.createServer(function(request, response){
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('My first node server...');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost:8888',
user : 'root',
password: '',
database: 'test'
});
connection.connect();
connection.query('SELECT * FROM tabel_test', function(err, rows, fields){
if (!err) {
console.log('The result is ', rows);
} else {
console.log('No results.');
}
});
connection.end();
response.end();
}).listen(8888);
The code seems fine, the exception says that you do not have the mysql module, that could be technically true.
Make sure you have the node_modules\mysql folder in the current working directory, or that you have installed it globally with npm install -g mysql.
By the way I suggested the package.json file, because in there you could define the required version of the mysql module. Then if you do npm intall in the folder, the enumerated dependencies will be downloaded to the current working directory. This also make it easier for others to use you code, if you put it into a git repository.
if you found the given path node/node_modules/mysql/lib
change the below line
connection.query('SELECT * FROM test_user', function(err, rows, fields)
connection.end();
Yosemite Mongo user working through a MEAN book. I've been following the steps exactly, but the MongoDB isn't connecting as expected. I installed Mongo once before to mess around with importing data, but didn't get too far. Below is all the Mongo related code I have besides package.json:
In app.js I have require('./app_server/models/db'); and in that folder I have:
var mongoose = require( 'mongoose' );
var dbURI = 'mongodb://localhost/Loc8r';
mongoose.connect(dbURI);
// CONNECTION EVENTS
mongoose.connection.on('connected', function () {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error',function (err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
console.log('Mongoose disconnected');
});
I am expecting to get
Express server listening on port 3000
Mongoose connected to mongodb://localhost/Loc8r
But instead get:
Mongoose disconnected
Mongoose connection error: Error: failed to connect to [localhost:27017]
I've tried changing a line to var dbURI = 'mongodb://localhost:3000/Loc8r'; because that's what my computer is using, but then get this error:
Mongoose disconnected
Mongoose connection error: Error: connection closed
Any help is much appreciated thanks.
Mongo was missing the folders it needed MongoDB not working. "ERROR: dbpath (/data/db) does not exist."
Then the server had to be run with "mongod"
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")