How to get the document count in MongoDB using NodeJS/express JS - javascript

I am trying to get the count of the documents in MongoDB collection but I am not getting the count.
Here's what I am trying:
//get the invoice count
Routes.route('/invoicescount').get((req, res) => {
invoicesDB.count({}, (err, count) => {
if (err) {
res.status(400).send(err);
} else {
const c = count;
res.status(200).send(c);
}
});
});
It doesn't give any value but in the console it gives this error:
error found: CastError: Cast to ObjectId failed for value
"invoicescount" at path "_id" for model "invoices"

i am using this function for getting the count of every collection:
var MongoClient = require('mongodb').MongoClient;
var dbName = "myName";
var port = "27017";
var host = "localhost";
function getNumOfDocs (collectionName, host, port, dbName, callback) {
MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){
if(error) return callback(error);
db.collection(collectionName).count({}, function(error, numOfDocs){
if(error) return callback(error);
db.close();
callback(null, numOfDocs);
});
});
}
and i call it:
getNumOfDocs("collName", host, port, dbName, function(err, count) {
if (err) {
return console.log(err.message);
}
console.log('number of documents', count);
});

Related

How to insert json data into mysql using node js

var express = require('express');
var app=express();
var length;
var affiliate = require('flipkart-affiliate');
var url = require('url');
var moment=require('moment');
var mysql = require('mysql');
var body;
var getUrl;
var product;
var offer;
var offer1;
var offer2;
var offer3;
var test1;
var test2;
var test3;
var title=[];
var description=[];
var startTime=[];
var endTime=[];
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'coupontest'
});
var client = affiliate.createClient({
FkAffId: 'anandhkum',
FkAffToken: 'eb030998c556443087d3b1a27ac569d0',
responseType: 'json'
});
client.getCategoryFeed({
trackingId: 'anandhkum'
}, function(err, result,getUrl){
if(!err){
body=JSON.parse(result);
getUrl=body.apiGroups.affiliate.apiListings.food_nutrition.availableVariants["v1.1.0"].get;
client.getProductsFeed({
url: getUrl
}, function(err, result){
if(!err){
}else {
console.log(err);
}
});
}
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.get('/',function (req,res) {
client.getAllOffers(null,function(err, resp){
if(!err){
offer=JSON.parse(resp);
test1=offer.allOffersList.length;
res.send(offer);
for(var i=0;i<test1;i++){
description[i]=offer.allOffersList[i].description;
startTime[i]=offer.allOffersList[i].startTime;
endTime[i]=offer.allOffersList[i].endTime;
}
var stmt = "INSERT INTO offers (description,start_time,end_time) VALUES ?";
connection.query(stmt, [description,startTime,endTime], function (err, result) {
if (err) throw err.message;
console.log("Number of records inserted: " + result.affectedRows);
});
}
else{
console.log(err);
}
});
});
app.listen(3000);
console.log("Listening to port 3000");
I'm getting the error
throw err; // Rethrow non-MySQL errors
^
ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' 3 ports - multi device charging', 'Universal Voltage', 'Best Price Ever', 'Ext' at line 1
When doing a prepared statement, you need a ? for each of the values you bind. E.g. INSERT INTO offers (description,start_time,end_time) VALUES (?, ?, ?, ?)
It might be worthwhile to take a look at using something like the knex.js module. It uses the mysql module underneath and does the sql binding under the hood.

nodejs TypeError: this.connect is not a function

When I start my nodejs application, it can't find a function which is really important: TypeError: this.connect is not a function
at C:\Users\Jonas\.AtomProjects\PoliticsBrowserGame\app\database.js:89:12
at tryToString (fs.js:456:3)
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:443:12)
This is my database class which I want to exist only once because I want only one connection for the application and not multiple connections.
var mysql = require('mysql');
var fs = require("fs");
var eventEmitter = require("./events.js");
function Database() {
this.connection;
this.poolCluster;
var host;
var username;
var password;
var db;
var config;
var clusterConfig = {
removeNodeErrorCount: 5,
restoreNodeTimeout: 1000,
defaultSelector: 'ORDER'
};
var poolConfig = {
acquireTimeout: 10000,
waitForConnections: false,
connectionLimit: 10,
queueLimit: 0
};
this.connect = function() {
this.connection = mysql.createConnection({
host: config.mysqlHost,
user: config.mysqlUsername,
password: config.mysqlPassword,
database: config.mysqlDb
});
this.connection.connect(function(err) {
if(err) {
console.error("Connection couldn't established at " + config.mysqlHost + " (user: " + config.mysqlUsername + ")"
+ "\nError: " + err);
return;
}
console.log("Connected to mysql server at " + config.mysqlHost + " (user: " + config.mysqlUsername + ")");
this.poolCluster = mysql.createPoolCluster(clusterConfig);
this.poolCluster.add("APP", poolConfig);
this.poolCluster.add("ACCOUNTS", poolConfig);
this.poolCluster.add("GAME", poolConfig);
console.log("Created Connection Clusters\n- APP\n- ACCOUNTs \n- GAME");
eventEmitter.emit("MysqlConnectionReady");
});
};
this.getMainConnection = function() {
return this.connection;
};
this.getAppConnection = function() {
this.poolCluster.getConnection("APP", 'ORDER', function(err, connection) {
if(err) throw err;
return connection;
});
};
this.getAccountsConnection = function() {
this.poolCluster.getConnection("ACCOUNTS", 'ORDER', function(err, connection) {
if(err) throw err;
return connection;
});
};
this.getGameConnection = function() {
this.poolCluster.getConnection("GAME", 'ORDER', function(err, connection) {
if(err) throw err;
return connection;
});
};
fs.readFile(process.cwd() + "/config.json", 'utf8', function(err, data) {
if(err) throw err;
config = JSON.parse(data);
this.connect();
});
}
module.exports = Database;
Fixed, thanks to Ajay and Lennart Hase.
But I have another problem too, in my code I set module.exports = Database;
When I want to use Database in another file its undefined. I want to use this in another file and I want to use only instance of that because I want only one connection for the app Im running.
Try changing this.connect, in the readFile callback this won't stands for you db instance. So we need to store this reference in some variable like var self = this
//filename is database.js
function Database() {
....
....
var self = this;
fs.readFile(process.cwd() + "/config.json", 'utf8', function(err, data) {
if(err) throw err;
config = JSON.parse(data);
self.connect();
});
....
}
module.exports = Database;
Update: Accessing this Database Module from outside.
var dbModule = require("./database.js");
var database = new dbModule();
// Give some time to read config.json and connect
database.getMainConnection();
I think your problem is that you're calling this within another method, try replacing the last part of your code with the following;
var self = this;
fs.readFile(process.cwd() + "/config.json", 'utf8', function(err, data) {
if(err) throw err;
config = JSON.parse(data);
self.connect();
});
this has a new definition within the callback method of the fs.readFile() method, hence you're trying to call a connect method within the callback method which obviously doesn't exist. You're actually trying to call the parent method, this would be a way to achieve this.

Matching mail and pass in mongodb node js

So, I'm new to all this and was developing a login and registration page. I can easily save the data to the database while registering through registration page, but the problem is I don't know what to do during login page. What type of statements do I have to use to match the entered email address with the email addresses of each document in the "employee" collection, and then check if the password is correctly entered.
Here is my express file main.js:
var express = require("express");
var app = express();
var connection = require("../connection");
module.exports = function(app){
app.get('/', function(req, res){
res.render("login.html");
});
app.get('/adduser', function(req, res){
res.render("login.html");
var name = req.param('name');
var email = req.param('email');
var employeeid = req.param('employeeid');
var password = req.param('password');
var position='';
var joining_date= '';
var active= 'Y';
console.log("Name: " + name + " Email: " + email + "Employee id: " +employeeid);
connection.add(name,email,employeeid,password,position,joining_date,active);
});
//CHECKING IF MAIL AND PASSWORD MATCHES
app.get('/checkuser', function(req, res){
var email = req.param('email');
var password = req.param('password');
console.log(" Email: " + email);
connection.check(email,password);
});
And this is the connection file, connection.js:
var add=function(uname,uemail,uemployeeid,upassword,uposition,ujoining_date,uactive) {
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('employees');
//Create some users
var data = {name:uname,email:uemail,employeeid:uemployeeid,password:upassword,position:uposition,joining_date:ujoining_date,active:uactive };
/* var user2 = {name: 'modulus user', age: 22, roles: ['user']};
var user3 = {name: 'modulus super admin', age: 92, roles: ['super-admin', 'admin', 'moderator', 'user']};*/
// Insert some users
collection.insert(data, function (err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "employees" collection. The documents inserted with "_id" are:', result.length, result);
}
db.close();
});
}
});
} //NOW CHECKING IF ENTERED EMAIL AND PASS MATCHES OR EMAIL EXISTS???
var check= function(uemail,upassword)
{
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
var collection = db.collection('employees');
collection.findOne({uemail:uemail}, function(err,doc){ //I HAVE NO IDEA WHAT TO DO HERE??
if(err) throw err;
if(doc)
console.log("Found: "+uemail+", pass=");
else
console.log("Not found: "+uemail);
db.close();
});
}
});
}
module.exports.add=add;
module.exports.check=check;
EDITED: THE FIX FOR THE ABOVE PROBLEM IS PROVIDED BY GMANIC BELOW..
Here is the fix, you are trying to match on uemail but you saved it as email. You could even take it a step further and match on the password at the same time.
exports.check = function(uemail, upassword)
{
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
var collection = db.collection('employees');
collection.findOne({ email: uemail, password: upassword }, function(err, doc){
if(err) throw err;
if(doc) {
console.log("Found: " + uemail + ", pass=" + upassword);
} else {
console.log("Not found: " + uemail);
}
db.close();
});
}
});
}
There are some best practices that you should add in, but to answer your question this should work.

Asynchronous function not returning callback for MongoDB connect

I have a MongoDB connect call that crashes a heroku app..
I have been editing what was originally localHost code (was working perfectly) to work with Heroku MongoDb addons (like MongoLab), but how do I get someDBcollectionVariable to work with someDBcollectionVariable.find()
//MongoDB
var mongodb = require('mongodb');
var db;
var MONGODB_URI = process.env.MONGOLAB_URI;
var PORT = process.env.PORT;
var testColl;
function dbConnect() {
return mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
if(err) throw err;
db = database;
var testColl = db.collection('test');
app.listen(PORT);
console.log('Listening on port ' + PORT);
return testColl;
});
}
//calls then look like
app.post('/add', function (req, res) {
testColl.insert(
{
"title" : req.body.title,
"quantity" : parseInt(req.body.quantity)
},
function (err, doc) {
getAll(res);
});
});
//and getAll looks like this
function getAll(res) {
testColl.find().sort( { value: 1 } ).toArray(function (err, docs) {
res.json({docs: docs});
});
}
Before moving that code inside dbConnect(), testColl.find.. was generating a ResponseError because the connect code was completing before the variable could be set?
Returning a value from an asynchronous function makes no sense. To use the a value, you need to pass it to a callback function. The same goes for errors (you can't throw asynchronously). A fixed version of your code could look like:
//MongoDB
var mongodb = require('mongodb');
var db;
var MONGODB_URI = process.env.MONGOLAB_URI;
var PORT = process.env.PORT;
var testColl;
function dbConnect(callback) {
mongodb.MongoClient.connect(MONGODB_URI, function (err, database) {
if (err) {
return callback(err);
}
db = database;
database.collection('test', function (err, testColl) {
if (err) {
return callback(err);
}
app.listen(PORT);
console.log('Listening on port ' + PORT);
callback(null, testColl);
});
});
}
//calls then look like
dbConnect(function (err, testColl) {
if (err) {
return console.error(err.stack || err.message);
}
testColl.find...
});

Last callback not being called using async

I cannot seem to get the last callback (commented as "optional callback") called to send the result back to the browser. Any pointers as to what I am doing wrong? I am using the following modules: async, restify and postgresql for node.js
console.log('Start');
var async = require('async');
var restify = require('restify');
var server = restify.createServer();
server.use(restify.bodyParser());
server.get('/user/creationdate/:username', function(req, res, next) {
var userName = req.params.username;
var record;
async.parallel([
function(callback){
getUserByName(userName, function(err, user) {
if (err) return callback(err);
record = user;
});
}
],
// optional callback
function(err){
console.log('5. Following record has been retrieved:' + record);
res.send(record);
});
next();
});
server.listen(8080, function () {
console.log('%s listening at %s', server.name, server.url);
});
handleError = function handleError(err) {
if(!err) { return false; }
else {
console.log('The following error occurred:' + err);
}
return true;
};
function getPgClient(){
var pg = require('pg');
var client = new pg.Client({
user: 'postgres',
password: 'password',
database: 'foobar',
host: '192.168.1.100',
port: 5432
});
client.on('drain', client.end.bind(client)); //disconnect client when all queries are finished
return client;
}
function getUserByName(userName, callback){
var client = getPgClient();
console.log('2. Trying to connect to DB');
client.connect(function(err) {
console.log('3. Error connecting to DB:' + handleError(err));
if(handleError(err)) return callback(err);
client.query("SELECT created_at FROM users WHERE username='" + userName + "'", function(err, result) {
if(handleError(err)) return;
console.log('4. Error occurred:' + err);
console.log(result);
console.log(callback);
callback(null, result);
})
});
}
I'm not sure why you're using async since you're only calling one asynchronous function. But the reason your callback isn't called is because you're not ending the first function by calling its callback:
async.parallel([
function(callback) {
getUserByName(userName, function(err, user) {
// call async callback with err and user
callback(err, user);
});
}
], function(err, record) {
console.log('5. Following record has been retrieved:' + record);
res.send(record);
});
Or, shorter:
async.parallel([
function(callback) {
getUserByName(callback);
}
], function(err, record) {
console.log('5. Following record has been retrieved:' + record);
res.send(record);
});
Or, in this case, even shorter (and without the need for async):
getUserByName(function(err, record) {
// handle error, or ...
console.log('5. Following record has been retrieved:' + record);
res.send(record);
});
Saw my mistake, missing the line where I should have returned the callback as in:
async.parallel([
function(callback){
getUserByName(userName, function(err, user) {
if (err) return callback(err);
record = user;
return callback(null, record);
});
}

Categories

Resources