"Collection is not defined" error on insert with mongodb - node.js

I am using mongodb in a nodejs app I am currently writing.
Upon running an insert in my code, I get the following error back: ReferenceError: collection is not defined at /home/safeuser/lunchand/routes/talktomongo.js:17:7
As far as I can tell from docs, simply running insert in a collection should create it! If I open mongo manually in my terminal and run show dbs I also never see lunchand in the list of dbs, just local and admin.
Here's the code I'm using. Line 17 is where the collection.insert is. Any help would be greatly appreciated.
//Declarations
var mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db,
server = new Server('localhost', 27017, {auto_reconnect: true}),
db = new Db('lunchand', server);
//Open database
db.open(function(_err, _db) {
if(!_err) {
console.log("Connected to lunchand DB");
db.collection('lunchers', {strict: true}, function(_err, _collection) {
if(_err) {
console.log("Lunchers collection doesn't exist! Let's fix that!");
var testLuncher = {username:"username",pwd:"password",officeLocation:"Office Location",teams:"teams",shark: true};
db.collection('lunchers', function(_err, _collection) {
collection.insert(testLuncher, {safe:true}, function(_err, _result) {});
});
} else {
console.log("Oh it exists");
}
});
} else {
console.log("Error Connecting to Station DB: " + _err);
}
});

try to add the name of the collection to the object something like this:
db.collection("lunchers").insert(testLuncher,function(err, element){
console.log("element inserted");
});
probably your code should look like:
var mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db,
server = new Server('localhost', 27017, {auto_reconnect: true}),
db = new Db('lunchand', server);
//Open database
db.open(function(_err, _db) {
if(!_err) {
db.collection('lunchers', {strict: true}, function(_err, _collection) {
if(_err) {
var testLuncher = {username:"username",pwd:"password",officeLocation:"Office Location",teams:"teams",shark: true};
db.collection("lunchers").insert(testLuncher,function(err, element){
console.log("element inserted");
});
} else {
console.log("Oh it exists");
}
});
} else {
console.log("Error Connecting to Station DB: " + _err);
}
});

I would guess that line 17 should actually be either db.collection.insert(... or _collection.insert(...

Related

How to select more than one matching data in MongoDB using Nodejs in Express

this is the code to find one matching data which works fine. But when i replace db.findOne({username: email} with db.find({username: email} I cannot see all the values with the specific email id.
This is my code to connect to the mongo database
var MongoClient = require('mongodb').MongoClient;
var db;
var connected = false;
/**Connects to the MongoDB Database with the provided URL**/
exports.connect = function(url, callback) {
MongoClient.connect(url, function(err, _db) {
if (err) { throw new Error('Could not connect: ' + err); }
db = _db;
connected = true;
console.log(connected + " is connected?");
callback(db);
});
};
/**Returns the collection on the selected database**/
exports.collection = function(name) {
if (!connected) {
throw new Error('Must connect to Mongo before calling "collection"');
}
return db.collection(name);
};
How can I access all the data related to a email id? Please help.. I am new to Mongodb

how to run a query SQL in node.js mysql

I have a syntax problem in a module, I fail to do the SQL query.
I initialize the module database in file.js, it responds with console.log 'Connected to the database', then sends the data to the module in Database.newData(data), when it enters in runQuery nothing happens, no errors or result, nothing!
I look in runQuery if this query was ok and if this, I think what happens is that there is an error in my logic of node, the idea is to connect to the database and use runQuery to run any query that you pass.
file.js
var DB = require('./modules/database');
var Database = new DB();
Database.newData(data);
database.js
var mysql = require('mysql'),
queries = require('./queries'),
connection;
var DB = function(){
var db_config = {
host: 'localhost',
user: 'diegoug',
password: 'qwertyuiop',
database: 'test'
};
connection = mysql.createConnection(db_config);
connection.connect(function(err) {
if(err) {
console.log('error when connecting to database:', err);
}
console.log('Connected to the database');
});
}
DB.prototype.runQuery = function(Query,Data,cb){
// Here not pass nothing
connection.query(
Query,
Data,
function(err, results){
debugger;
if (err)throw err;
cb(results);
}
);
// look here if the query was well written and if it is, what happens is that it's simply not running anything in the connection
}
DB.prototype.newData = function(data){
var Query = queries.SQLNEWDATA,
data = [data];
var res = this.runQuery(Query,data);
console.log(res);
}
module.exports = DB;

How to properly pass mysql connection to routes with express.js

I am trying to figure out the best way to pass a mysql connection (using node-mysql) between my routes for express.js. I am dynamically adding each route (using a for each file loop in routes), meaning I can't just pass in the connection to routes that need it. I either need to pass it to every route or none at all. I didn't like the idea of passing it to ones that dont need it so I created a dbConnection.js that the routes can individually import if they need. The problem is that I dont think I am doing it correctly. As of now, my dbConnection.js contains:
var mysql = require('mysql');
var db = null;
module.exports = function () {
if(!db) {
db = mysql.createConnection({
socketPath: '/tmp/mysql.sock',
user: '*********',
password: '*********',
database: '**********'
});
}
return db;
};
And I am importing it into each route using:
var db = require('../dbConnection.js');
var connection = new db();
But I would like to do it like this:
var connection = require('../dbConnection.js');
When I try it like this, however, I get an error saying connection has no method 'query' when I try to make a query.
I find it more reliable to use node-mysql's pool object. Here's how I set mine up. I use environment variable for database information. Keeps it out of the repo.
database.js
var mysql = require('mysql');
var pool = mysql.createPool({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASS,
database: process.env.MYSQL_DB,
connectionLimit: 10,
supportBigNumbers: true
});
// Get records from a city
exports.getRecords = function(city, callback) {
var sql = "SELECT name FROM users WHERE city=?";
// get a connection from the pool
pool.getConnection(function(err, connection) {
if(err) { console.log(err); callback(true); return; }
// make the query
connection.query(sql, [city], function(err, results) {
connection.release();
if(err) { console.log(err); callback(true); return; }
callback(false, results);
});
});
};
Route
var db = require('../database');
exports.GET = function(req, res) {
db.getRecords("San Francisco", function(err, results) {
if(err) { res.send(500,"Server Error"); return;
// Respond with results as JSON
res.send(results);
});
};
your solution will work if use db() instead of new db(), which returns an object and not the db connection
var db = require('../dbConnection.js');
//var connection = new db();
var connection = db();

node.js application - integrate mongodb in appfog

I am starting to use appfog services in order to host node application.
I am getting trouble trying to use mongodb in my application.
In you tutorial here: https://docs.appfog.com/services/mongodb#walkthrough it is written to connect mongodb like this:
require('mongodb').connect(mongourl, ...
while mogourl is the url generated by the generate_mongo_url function.
The problem is that I am using newer api (I think) and I cannot pass url to the open method. This is how I am using mongodb:
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) { ...
Where and how can I use the generated mongourl? How can I pass the credentials and the mongo variable used in generate_mongo_url function?
UPDATE
According to #mjhm suggestion, this is my open function:
var mongoService = null;
if(process.env.VCAP_SERVICES){
var env = JSON.parse(process.env.VCAP_SERVICES);
mongoService = env["mongodb-1.8"][0]["credentials"];
} else {
mongoService = {
"hostname": "localhost",
"port": 27017,
"isLocal": true,
"username": "",
"password": "",
"name": ""
};
}
this.mongoClient.open(function(err, mongoClient) {
if (!err) {
console.log("Open DB Success");
var db = mongoClient.db(DB_NAME);
if (!mongoService.isLocal) {
db.authenticate(mongoService.username,
mongoService.password, function (err, result) {
if (!err) {
console.log("Authenticate DB Success");
doAction();
} else {
console.log("Authenticate DB Error: " + err);
}
});
} else {
doAction();
}
} else {
console.log("Open DB Error: " + err);
}
});
When I am running this code on appfog, I am waiting a lot of time (more then 20 seconds) and then I get:
$ curl myappname.eu01.aws.af.cm/list
curl: (52) Empty reply from server
Any idea what is wrong?
What you are looking for is the MongoClient.connect function
http://mongodb.github.com/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect
It takes the url you are talking about.
the URL where your client / driver wants to connect to was 'localhost'. I replaced it with a
variable mongoUrl
var mongoClient = new MongoClient(new Server(mongoUrl, 27017));
You need to authenticate after opening the database. The way to think of it is that authentication happens against the database not the connection, so as you discovered the generate_mongo_url function isn't very useful.
For example:
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
var db = mongoClient.db('test');
db.authenticate('me', 'mypwd', function (err, result) {
var coll = db.collection('query_example3');
coll.find().toArray(function(err, result) {
console.log(result);
process.exit(0);
});
});
});

MongoDb driver in nodejs does not call open function callback

In the following code the function passed to the open function never runs, then the istruction console.log('open!') in the following code never runs:
var mongo = require("mongodb");
var Db = mongo.Db;
var connection = mongo.Connection;
var Server = mongo.Server;
var client = new Db('test', new Server("localhost", 27017, {}));
var test = function (err, collection) {
collection.insert({a:2}, function(err, docs) {
collection.count(function(err, count) {
test.assertEquals(1, count);
});
// Locate all the entries using find
collection.find().toArray(function(err, results) {
test.assertEquals(1, results.length);
test.assertTrue(results[0].a === 2);
// Let's close the db
client.close();
});
});
};
client.open(function(err, p_client) {
console.log('open!');
client.collection('test_insert', test);
});
From the log I see that the connection is accepted:
Sun March 11 16:52:01 [initandlisten] accepted connection from 127.0.0.1:61875 # 1
Mongodb great works from interactive shell.
can someone tell me any suggestion?
thank you!
Copy/paste this...it should work without any problems:
var client = new Db('test', new Server("localhost", 27017, {}), {});
client.open(function(err, client) {
console.log('open!');
}
Also, don't forget to authenticate after opening the connection.
var client = new Db('test', new Server("localhost", 27017, {}), {});
client.open(function(err, client) {
console.log('open!');
client.authenticate('admin', 'admin', function(err, result) {
// Authenticated
});
}

Resources