I am getting an error on node.js, and I cannot identify why. Can anybody help me? If I add only 1 data from the array it gets added to the database. However, when I add other inputs, it displays an error in node.js and doesn't get saved in my database.
var express = require('express');
var app = express();
app.get('/register/*', handleGetRequest); //how do I pass usrName here?
app.use(express.static('public'));
app.listen(5000);
function handleGetRequest(request, response){
var pathArray = request.url.split("/");
var pathEnd = pathArray[pathArray.length - 1];
if(pathEnd === 'register'){
response.send("{working}");
//console.log(request.body.usrName);
}
else
var registerArray = pathEnd.split("&");
response.send(JSON.stringify(registerArray));
saveToDb(registerArray);
// response.send("{error: 'Path not recognized'}");
}
function saveToDb(registerArray){
for (var i = 0; i < registerArray.length; i++) {
console.log(registerArray[i]);
}
var mysql = require('mysql');
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'customer',
port: 6000
});
con.connect();
addData();
function addData(){
var query = con.query(
"INSERT INTO cust (id,LastName,FirstName) VALUES
('001,"+registerArray[0]+"," +registerArray[1]+"');",function(err, result,
fields){
if (err) throw err;
console.log('results' , result);
}
);
}
//Close the connection
con.end();
}
You are missing single quotes in your SQL statement that cause the problem. The code should look like this:
function addData(){
var query = con.query(
"INSERT INTO cust (id,LastName,FirstName) VALUES
('001','"+registerArray[0]+"','" +registerArray[1]+"');",
function(err, result, fields) {
if (err) throw err;
console.log('results' , result);
}
);
}
I have two files named login.js and dbMySql.js.
login.js is the main file that will run dbMySql.js, which is a submodule for the DB connection.
I can run getQuery() from dbMySql.js by using object.method call.
getQuery() also works fine and retrieves data from the database.
How can I get this data to my Main module from the database module? How can I return res variable to main function in login.js module
Code For login.js:
var MySqlConnect = require('./dbMySql');
var app = express();
var dbConnect = MySqlConnect("localhost", "root", "root", "mydb");
dbConnect.getQuery("select * from `test`");
console.log(dbConnect.resD);
Code For dbMySql.js:
function MySqlConnect(dbhost, dbuser, dbpassword, dbname) {
var MySqlConnect = require('mysql');
var con;
this.dbhost = dbhost;
this.dbuser = dbuser;
this.dbpassword = dbpassword;
this.dbname = dbname;
this.resultData = 'Def';
con = MySqlConnect.createConnection({
host: dbhost,
user: dbuser,
password: dbpassword,
database: dbname
})
con.connect(function (err) {
if (err) throw err;
})
function getQuery(query1) {
con.query(query1, function (err, res) {
if (err) throw err;
})
return {
resD: res
};
}
return {
getQuery: getQuery,
};
};
module.exports = MySqlConnect;
I want Retrieved Data in Main module via return method or any that will run successfully.
Vary Simple Answer I have found by run and execute after efforts.
just pass res form db to callback function parameter and run this fucntion from main module
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.
How do I connect to mongodb with node.js?
I have the node-mongodb-native driver.
There's apparently 0 documentation.
Is it something like this?
var mongo = require('mongodb/lib/mongodb');
var Db= new mongo.Db( dbname, new mongo.Server( 'mongolab.com', 27017, {}), {});
Where do I put the username and the password?
Also how do I insert something?
Thanks.
Per the source:
After connecting:
Db.authenticate(user, password, function(err, res) {
// callback
});
Everyone should use this source link:
http://mongodb.github.com/node-mongodb-native/contents.html
Answer to the question:
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
var db = new Db('integration_tests', new Server("127.0.0.1", 27017,
{auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});
// Establish connection to db
db.open(function(err, db) {
assert.equal(null, err);
// Add a user to the database
db.addUser('user', 'name', function(err, result) {
assert.equal(null, err);
// Authenticate
db.authenticate('user', 'name', function(err, result) {
assert.equal(true, result);
db.close();
});
});
});
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://'+DATABASEUSERNAME+':'+DATABASEPASSWORD+'#'+DATABASEHOST+':'DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
//for local server
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DATABASEHOST+':'+DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
I find using a Mongo url handy. I store the URL in an environment variable and use that to configure servers whilst the development version uses a default url with no password.
The URL has the form:
export MONGODB_DATABASE_URL=mongodb://USERNAME:PASSWORD#DBHOST:DBPORT/DBNAME
Code to connect this way:
var DATABASE_URL = process.env.MONGODB_DATABASE_URL || mongodb.DEFAULT_URL;
mongo_connect(DATABASE_URL, mongodb_server_options,
function(err, db) {
if(db && !err) {
console.log("connected to mongodb" + " " + lobby_db);
}
else if(err) {
console.log("NOT connected to mongodb " + err + " " + lobby_db);
}
});
My version:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://user:pass#dhost:port/baseName', function(err, db) {
if (err) {
console.error(err);
}
var collection = db.collection('collectionName');
collection.find().toArray(function(err, docs) {
console.log(docs);
});
});
I recommend mongoskin I just created.
var mongo = require('mongoskin');
var db = mongo.db('admin:pass#localhost/mydb?auto_reconnnect');
db.collection('mycollection').find().toArray(function(err, items){
// do something with items
});
Is mongoskin sync? Nop, it is async.
Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:
var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
assert = require('assert');
var user = 'user';
var password = 'password';
MongoClient.connect('mongodb://'+user+':'+password+'#localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
if(err){
console.log("Auth Failed");
return;
}
console.log("Connected");
db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
console.log(doc['_id']);
}
});
});
db.close();
});
This worked for me:
Db.admin().authenticate(user, password, function() {} );
You can do it like this
var db = require('mongo-lite').connect('mongodb://localhost/test')
more details ...
if you continue to have problems with the native driver, you can also check out sleepy mongoose. It's a python REST server that you can simply access with node request to get to your Mongo instance.
http://www.snailinaturtleneck.com/blog/2010/02/22/sleepy-mongoose-a-mongodb-rest-interface/
With the link provided by #mattdlockyer as reference, this worked for me:
var mongo = require('mongodb');
var server = new mongo.Server(host, port, options);
db = new mongo.Db(mydb, server, {fsync:true});
db.open(function(err, db) {
if(!err) {
console.log("Connected to database");
db.authenticate(user, password, function(err, res) {
if(!err) {
console.log("Authenticated");
} else {
console.log("Error in authentication.");
console.log(err);
}
});
} else {
console.log("Error in open().");
console.log(err);
};
});
exports.testMongo = function(req, res){
db.collection( mycollection, function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
Slight typo with Chris' answer.
Db.authenticate(user, password, function({ // callback }));
should be
Db.authenticate(user, password, function(){ // callback } );
Also depending on your mongodb configuration, you may need to connect to admin and auth there first before going to a different database. This will be the case if you don't add a user to the database you're trying to access. Then you can auth via admin and then switch db and then read or write at will.
const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myProject';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
// the following code examples can be pasted here...
return 'done.';
}
main()
//what to do next
.then(console.log)
//if there is an error
.catch(console.error)
// what to do in the end(function result won't matter here, it will execute always).
.finally(() => client.close());
you can find more in the documentation here: https://mongodb.github.io/node-mongodb-native/4.1/
I'm using Mongoose to connect to mongodb.
Install mongoose npm using following command
npm install mongoose
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/database_name', function(err){
if(err){
console.log('database not connected');
}
});
var Schema = mongoose.Schema;
var userschema = new Schema ({});
var user = mongoose.model('collection_name', userschema);
we can use the queries like this
user.find({},function(err,data){
if(err){
console.log(err);
}
console.log(data);
});
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.