I am a beginner for Node.js. Please help to fix this.
Without giving WHERE clause update is working fine. Below is the script without "WHERE" clause:
var post = {name: 'Amit', mobile:'123456'};
var query = connection.query('UPDATE contacts SET ? ', post , function(err, result) {});
console.log(query.sql);
Output:
Now I added 'WHERE' clause..getting error:
var post = {name: 'Amit', mobile:'123456'};
var condition = {id:4};
var query = connection.query('UPDATE contacts SET ? ',post,' WHERE '+ condition , function(err, result) {});
console.log(query.sql);
Output:
According to the api, your should write you query like this:
connection.query('UPDATE contacts SET Name = ?,Mobile=? WHERE yourCondition = ?', [post.name,post.mobile,condition], function(err, result) {})
Try that code:
var post = {name: 'Amit', mobile:'123456'};
var condition = {id:4};
var query = connection.query('UPDATE contacts SET ? WHERE ?', [post, condition] , function(err, result) {});
console.log(query.sql);
try this ,it workd for me
connection.query('UPDATE nodeDB.USER SET USER_PASSWORD :Pass WHERE USER_NAME :Name',
{Name: 'max',Pass: '123'}, function(err, rows) {
});
Check My code also work for you.
router.all('/setLoginDetails', function (req, res) {
if(req.method == 'POST')
{
var Req = req.body;
}
else
{
var Req = req.query;
}
if(Req.lang == undefined || Req.lang == 'en')
{
const message = require('../lang/messages_en.json');
}
if(Req.id == undefined || Req.id == '')
{
return res.json({"success" : false, "Message" : message.REQUIRED , "data" : {} });
}
qb.select('id')
.where({id: Req.id})
.get('table', (err,rows) => {
if (err || rows.length == 0)
{
return res.json({"success" : false, "Message" : "No data found", "data" : Response});
}
else
{
_.each(rows, function(record) {
var token = tokenGenerate();
qb.update('token', {token: token}, {driver_id:record.id}, (err, result) => {
if (err) return console.error(err);
});
qb.select('*').where({driver_id: record.id}).get(model.DriverLogin, (err,rows) => {
var lat = Req.lat;
var lng = Req.lng;
if(Req.lat == '')
{
lat = 0.0;
}
if(Req.lng == '')
{
lng = 0.0;
}
var updateData = {lat : lat ,lng : lng, status : 'free', screen : Req.device_info, driver_id : record.id};
if(rows.length > 0)
{
qb.update('localtion', updateData, {driver_id:record.id}, (err, result) => {
if (err) return console.error(err);
});
}
else
{
qb.insert(model.DriverLogin, updateData, (err, res) => {
if (err) return console.error(err);
});
}
});
});
return res.json({"success" : true, "Message" : "Data Updated", "data" : Response});
}
}
);
});
Related
I am trying to do the stripe payment using nodejs and I am getting the following errors. One in console and one in web app UI in the browser. What are the reasons?
Also I am trying to use req.user property details which are saved in mongoDB.
I am getting the console error as : (node:6344) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'subscriptionPlan' of undefined
and on browser =>
Error: You cannot use a Stripe token more than once: tok_1IJggu*******************.
Below is my code:
router.post('/processPayment/:priceID', (req, res) => {
console.log("plan Token = "+ req.body.stripeToken);
console.log("plan Email = "+ req.body.stripeEmail);
var dateFormated, dateFormated2;
return stripe2.customers.create({
source: req.body.stripeToken,
email: req.body.stripeEmail
}).then(customer => {
stripe2.subscriptions.create({
customer: customer.id,
items: [
{
plan: req.params.priceID
}
]
}).then(subscription => {
console.log("subscription.status = "+ subscription.status);
dateFormated = new Date();
dateFormated2 = new Date();
console.log(dateFormated2.getMinutes() +' '+dateFormated2.getHours()+' '+dateFormated2.getDate() + ' * *');
var j = schedule.scheduleJob(dateFormated2.getMinutes() +' '+dateFormated2.getHours()+' '+dateFormated2.getDate() + ' * *',function(){
var snm = new Date();
return stripe2.subscriptions.retrieve(req.user.subsID)
.then(subsData => {
console.log("Status = "+ subsData.status);
if(subsData.status == 'active')
{
User.findOneAndUpdate({_id:req.user.id},
{$set: {"subscriptionDuplicateDate":req.user.subscriptionNextMonth }},
function (error, data) {
if (error) {
console.log(error);
return res.render("error",{error:error});
}
else if(req.user.subscriptionPlan == '$299' || req.user.subscriptionPlan == '$499' || req.user.subscriptionPlan == '$999')
{
snm = snm.setMonth(snm.getMonth() + 1);
console.log("snm = "+ snm);
User.findOneAndUpdate({_id:req.user.id},
{$set: {"subscriptionNextMonth" : new Date(snm.toLocaleString())}},
function (error, data) {
if (error) {
console.log(error);
return res.render("error",{error:error});
}
})
console.log('Your scheduled job every month');
}
else if(req.user.subscriptionPlan == '$2990' || req.user.subscriptionPlan == '$4990' || req.user.subscriptionPlan == '$9990')
{
snm = snm.setFullYear(snm.getFullYear() + 1);
console.log("snm = "+ snm);
User.findOneAndUpdate({_id:req.user.id},
{$set: {"subscriptionNextMonth" : new Date(snm.toLocaleString())}},
function (error, data) {
if (error) {
console.log(error);
return res.render("error",{error:error});
}
})
console.log('Your scheduled job every year');
}
})
}
else {
User.findOneAndUpdate({_id:req.user.id},
{$set: {"subscriptionTotalCount" : 0}},
function (error, data) {
if (error) {
console.log(error);
return res.render("error",{error:error});
}
})
}
}).catch(err => {
res.render('error', {message: err});
});
});
if(req.user.subscriptionPlan == '$299' || req.user.subscriptionPlan == '$499' || req.user.subscriptionPlan == '$999')
{
User.findOneAndUpdate({_id:req.user.id},
{$set: {"subscriptionDate":dateFormated,
"subscriptionDuplicateDate":dateFormated,
"subscriptionNextMonth":new Date(dateFormated.setMonth(dateFormated.getMonth() + 1))}},
function (error, data) {
if(data)
console.log("subscription date set");
})
}
else if(req.user.subscriptionPlan == '$2990' || req.user.subscriptionPlan == '$4990' || req.user.subscriptionPlan == '$9990')
{
User.findOneAndUpdate({_id:req.user.id},
{$set: {"subscriptionDate":dateFormated,
"subscriptionDuplicateDate":dateFormated,
"subscriptionNextMonth":new Date(dateFormated.setFullYear(dateFormated.getFullYear() + 1))}},
function (error, data) {
if(data)
console.log("subscription date set");
})
}
// console.log("subscription.items = "+ JSON.stringify(subscription.items));
console.dir(subscription);
res.redirect('/thankyou/0d4a3bc9cd71c4500584f01e7ce74cc6f2a4967ca266f3b7578ff29bd640dbbc/'+customer.id+'/'+subscription.id);
})
}).catch(err => {
res.render('error', {message: err});
});
});
I've added API requests which would retrieve data from MongoDB I believe. Whilst no issues arise when running the code, the pages do not show any data; I just get an error message (retrieved from a separate piece of code) stating the page cannot be found.
This is the code from my Locations controller:
module.exports.homelist = function(req, res){
var requestOptions, path;
path = '/api/locations';
requestOptions = {
url : apiOptions.server + path,
method : "GET",
json : {},
qs : {
lng : -0.7992599,
lat : 51.378091,
maxDistance : 20
}
};
request (
requestOptions,
function(err, response, body) {
var i, data;
data = body;
if(response.statusCode === 200 && data.length){
for (i=0; i<data.length; i++) {
data[i].distance = _formatDistance(data[i].distance);
}
}
renderLocHomepage(req, res, body);
}
);
var _formatDistance = function (distance){
var numDistance, unit;
if (distance > 1){
numDistance = parseFloat(distance).toFixed(1);
unit = 'km';
} else {
numDistance = parseInt(distance * 1000,10);
unit = 'm';
}
return numDistance + unit;
}
};
var renderLocHomepage = function(req, res, responseBody){
var message;
if(!(responseBody instanceof Array)){
message = "API lookup error";
responseBody = [];
} else {
if (!responseBody.length) {
message = "No places found nearby";
}
}
res.render('location', {
title: 'Location Title 2',
pageHeader: {
title: 'fuiewhf',
strapline: 'sdjkcdivfdvdj'
},
sidebar: "efvibjdmkdsuidjvifdvhiskfbvzd",
locations: responseBody,
message: message
});
};
/* GET 'Locations List' page*/
module.exports.locationsList = function(req, res) {
res.render('locations-list', {title: 'Locations List'});
};
module.exports.locationInfo = function(req, res){
renderDetailPage(req, res);
};
var renderDetailPage = function (req, res, locDetail){
res.render('location-info', {
title: locDetail.name,
pageHeader: {title: locDetail.name},
sidebar: {
context: 'is on Loc8r because it has some accessible wifi and space to sit',
callToAction: 'If you\'ve been and you like it or don\'t, please leave a review'
},
location: locDetail
});
};
/*GET 'Location info' page */
module.exports.locationInfo = function(req, res){
var requestOptions, path;
path = "/api/locations/" + req.params.locationid;
requestOptions = {
url : apiOptions.server + path,
method : "GET",
json : {}
};
request (requestOptions, function(err, response, body) {
var data = body;
if (response.statusCode === 200){
data.coords = {
lng : body.coords[0],
lat : body.coords[1],
};
renderDetailPage(req, res, data);
} else{
_showError(req, res, response.statusCode);
}
}
);
};
module.exports.locationsListByDistance = function(req, res){
var lng = parseFloat(req.query.lng);
var lat = parseFloat(req.query.lat);
var point = {
type: "Point",
coordinates: [lng, lat]
};
var geoOptions = {
spherical: true,
maxDistance: theEarth.getRadsFromDistance(20),
num: 10
};
if ((!lng && lng!==0) || (!lat && lat!==0)) {
sendJsonResponse(res, 404, {
"message": "lng and lat query parameters are required"
});
return;
}
Location.geoNear(point, geoOptions, function(err, results, stats){
var locations = [];
if (err) {
sendJsonResponse(res, 404, err);
} else {
results.forEach(function(doc) {
locations.push({
distance: theEarth.getDistanceFromRads(doc.dis),
name: doc.obj.name,
address: doc.obj.address,
rating: doc.obj.rating,
facilities: doc.obj.facilities,
_id: doc.obj._id
});
});
sendJsonResponse(res, 200, locations);
}
});
};
var _formatDistance = function (distance){
var numDistance, unit;
if (distance > 1){
numDistance = parseFloat(distance).toFixed(1);
unit = 'km';
} else {
numDistance = parseInt(distance * 1000,10);
unit = 'm';
}
return numDistance + unit;
};
//defining a call to an API
var requestOptions = {
url: "", //define URL of API call to be made
method: "GET", //set request method
json: {},
qs: {
offset: 20
}
};
request(requestOptions, function(err, response, body) {
if(err){
console.log(err);
} else if(response.statusCode === 200) {
console.log(body);
} else {
console.log(response.statusCode);
}
});
//Create a new reusable function to get location information
var getLocationInfo = function(req, res, callback) {
var requestOptions, path;
path = "/api/locations/" + req.params.locationid;
requestOptions = {
url : apiOptions.server + path,
method : "GET",
json : {}
};
request (
requestOptions,
function(err, response, body) {
var data = body;
if (response.statusCode === 200) {
data.coords = {
lng : body.coords[0],
lat : body.coords[1]
};
callback(req, res, data);
} else {
_showError(req, res, response.statusCode);
}
}
);
};
module.exports.locationInfo = function(req, res){
getLocationInfo(req, res, function (req, res, responseData){
renderDetailPage(req, res, responseData);
});
};
In renderHomepage you have res.render('/'... but res.render takes as first parameter the name of the file you want to render (minus the file extension):
res.render('index', ...
if your homepage is under views/index.ejs for example.
Even though I have searched for the solution of this error and i found some answers but none of them helped me fix this error, Error: NJS-012: encountered invalid bind data type in parameter 2.Maybe, one error can occur in a different scenarios.
Stored procedure definition
create or replace PROCEDURE SP_MEAL_GETMEALTYPES
(
p_DataSource OUT Sys_RefCursor
)
AS
BEGIN
OPEN p_DataSource FOR
select mealtypeid,description from mealtypes;
END;
File name: menusStoredProc.js
"use strict";
var dbParams = require('../../oracle/dbParams');
function storedProcs() {
this.SP_USER_GETMENUS = {
name: 'sp_meal_getmealtypes',
params: {
dataSource: {val: null, type: dbParams.CURSOR, dir: dbParams.BIND_OUT}
},
resultSetColumns: ['mealTypeId','description']
}
}
module.exports = storedProcs;
File name: menus.js
var express = require('express');
var MenusStoreProc = require('../storedProcedures/menusStoredProc');
var oraDbAssist = require('../../oracle/oracleDbAssist');
var router = express.Router();
router.get('/getmenus', (req, res, next) => {
var sp = new MenusStoreProc().SP_USER_GETMENUS;
oraDbAssist.getConnection(function (err, conn) {
if (err)
return console.log('Connecting to db failed - ' + err);
oraDbAssist.executeSqlWithConn(sp, false, conn, function (err, menus) {
if (err)
return console.log('Executing ' + sp.name + ' failed - ' + err);
res.status(200).json(JSON.stringify(menus));
});
});
});
module.exports = router;
Function definition added - executeSqlWithConn
function executeSqlWithConn(sp, autoCommit, connection, next) {
var sql = createProcedureSqlString(sp.name, sp.params);
var params = buildParams(sp.params);
connection.execute(sql, params, {autoCommit: autoCommit}, function(err, result) {
if (err) {
next(err, null);
return;
}
var allRows = [];
var numRows = 50; // number of rows to return from each call to getRows()
for(var attributeName in result.outBinds) {
if(result.outBinds[attributeName] && result.outBinds[attributeName].metaData) { // db response is a result set
function fetchRowsFromResultSet(pResultSet, pNumRows) {
pResultSet.getRows(pNumRows, function(readErr, rows) {
if(err) {
pResultSet.close(function (err) { // always close the result set
next(readErr);
});
return;
}
allRows.push(rows);
if (rows.length === pNumRows) {
fetchRowsFromResultSet(result.outBinds[attributeName], numRows);
return;
}
var allRowsResult = Array.prototype.concat.apply([], allRows);
generateJsonFromDbResultSet(pResultSet.metaData, allRowsResult, sp, function(resultSet) {
pResultSet.close(function (err) { // always close the result set
next(null, resultSet);
});
});
});
}
fetchRowsFromResultSet(result.outBinds[attributeName], numRows);
return;
}
}
next(null, result.outBinds);
});
}
Function definition added - buildParams
function buildParams(params) {
for(var attributeName in params) {
params[attributeName].val = typeof params[attributeName].val === 'undefined' ? null : params[attributeName].val;
if(params[attributeName].type.is(dbParams.DATE))
params[attributeName].val = params[attributeName].val ? new Date(params[attributeName].val) : null;
params[attributeName].type = params[attributeName].type.value;
params[attributeName].dir = params[attributeName].dir.value;
}
return params;
}
Any help, dear members ?
I have the following code:
var method = PushLoop.prototype;
var agent = require('./_header')
var request = require('request');
var User = require('../models/user_model.js');
var Message = require('../models/message_model.js');
var async = require('async')
function PushLoop() {};
method.startPushLoop = function() {
getUserList()
function getUserList() {
User.find({}, function(err, users) {
if (err) throw err;
if (users.length > 0) {
getUserMessages(users)
} else {
setTimeout(getUserList, 3000)
}
});
}
function getUserMessages(users) {
// console.log("getUserMessages")
async.eachSeries(users, function (user, callback) {
var params = {
email: user.email,
pwd: user.password,
token: user.device_token
}
messageRequest(params)
callback();
}, function (err) {
if (err) {
console.log(err)
setTimeout(getUserList, 3000)
}
});
}
function messageRequest(params) {
var url = "https://voip.ms/api/v1/rest.php?api_username="+ params.email +"&api_password="+ params.pwd +"&method=getSMS&type=1&limit=5"
request(url, function(err, response, body){
if (!err) {
var responseObject = JSON.parse(body);
var messages = responseObject.sms
if (responseObject["status"] == "success") {
async.eachSeries(messages, function(message, callback){
console.log(params.token)
saveMessage(message, params.token)
callback();
}, function(err) {
if (err) {
console.log(err)
}
// setTimeout(getUserList, 3000)
})
} else {
// setTimeout(getUserList, 3000)
}
} else {
console.log(err)
// setTimeout(getUserList, 3000)
}
});
setTimeout(getUserList, 3000)
}
function saveMessage(message, token) {
// { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } }
// Message.find({ $and: [{ message_id: message.id}, {device_token: token}]}, function (err, doc){
Message.findOne({message_id: message.id}, function (err, doc){
if (!doc) {
console.log('emtpy today')
var m = new Message({
message_id: message.id,
did: message.did,
contact: message.contact,
message: message.message,
date: message.date,
created_at: new Date().toLocaleString(),
updated_at: new Date().toLocaleString(),
device_token: token
});
m.save(function(e) {
if (e) {
console.log(e)
} else {
agent.createMessage()
.device(token)
.alert(message.message)
.set('contact', message.contact)
.set('did', message.did)
.set('id', message.id)
.set('date', message.date)
.set('message', message.message)
.send();
}
});
}
}) //.limit(1);
}
};
module.exports = PushLoop;
Which actually works perfectly fine in my development environment - However in production (i'm using Openshift) the mongo documents get saved in an endless loop so it looks like the (if (!doc)) condition always return true therefore the document gets created each time. Not sure if this could be a mongoose issue - I also tried the "find" method instead of "findOne". My dev env has node 0.12.7 and Openshift has 0.10.x - this could be the issue, and i'm still investigating - but if anybody can spot an error I cannot see in my logic/code please let me know
thanks!
I solved this issue by using a "series" like pattern and using the shift method on the users array. The mongoose upsert findOneOrCreate is good however if there is a found document, the document is returned, if one isn't found and therefore created, it's also returned. Therefore I could not distinguish between the newly insert doc vs. a found doc, so used the same findOne function which returns null if no doc is found I just create it and send the push notification. Still abit ugly, and I know I could have used promises or the async lib, might refactor in the future. This works for now
function PushLoop() {};
var results = [];
method.go = function() {
var userArr = [];
startLoop()
function startLoop() {
User.find({},function(err, users) {
if (err) throw err;
users.forEach(function(u) {
userArr.push(u)
})
function async(arg, callback) {
var url = "https://voip.ms/api/v1/rest.php?api_username="+ arg.email +"&api_password="+ arg.password +"&method=getSMS&type=1&limit=5"
request.get(url, {timeout: 30000}, function(err, response, body){
if (!err) {
var responseObject = JSON.parse(body);
var messages = responseObject.sms
var status = responseObject.status
if (status === "success") {
messages.forEach(function(m) {
var message = new Message({
message_id: m.id,
did: m.did,
contact: m.contact,
message: m.message,
date: m.date,
created_at: new Date().toLocaleString(),
updated_at: new Date().toLocaleString(),
device_token: arg.device_token
});
var query = { $and : [{message_id: m.id}, {device_token: arg.device_token}] }
var query1 = { message_id: m.id }
Message.findOne(query).lean().exec(function (err, doc){
if (!doc || doc == null) {
message.save(function(e) {
console.log("message saved")
if (e) {
console.log("there is an error")
console.log(e)
} else {
console.log(message.device_token)
var messageStringCleaned = message.message.toString().replace(/\\/g,"");
var payload = {
"contact" : message.contact,
"did" : message.did,
"id" : message.message_id,
"date" : message.date,
"message" : messageStringCleaned
}
var note = new apns.Notification();
var myDevice = new apns.Device(message.device_token);
note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge = 3;
note.alert = messageStringCleaned;
note.payload = payload;
apnsConnection.pushNotification(note, myDevice);
}
})
}
});
});
}
else {
console.log(err)
}
}
});
setTimeout(function() {
callback(arg + "testing 12");
}, 1000);
}
// Final task (same in all the examples)
function series(item) {
if(item) {
async( item, function(result) {
results.push(result);
return series(userArr.shift());
});
} else {
return final();
}
}
function final() {
console.log('Done');
startLoop();
}
series(userArr.shift())
});
}
}
module.exports = PushLoop;
I'm trying to traverse a collection and update an array for each document.
What am I doing wrong below?
var MongoClient = require('mongodb').MongoClient;
var removeLowestHWScore = function(scores) {
var lowestHWID = -1;
for(var i=0;i<scores.length; i++) {
if (scores[i].type === 'homework') {
if (lowestHWID === -1) {
lowestHWID = i;
} else if (scores[i].score < scores[lowestHWID].score) {
lowestHWID = i;
}
}
}
scores.splice(lowestHWID);
return scores;
};
var callback = function(err, r) {
console.log('updated record');
};
var updateScore = function(err, doc) {
var updatedScores = removeLowestHWScore(doc.scores);
collection.updateOne({_id:doc._id},
{$set: {scores: updatedScores }},
callback);
};
MongoClient.connect('mongodb://localhost:27017/school', function(err, db) {
if(err) throw err;
var collection = db.collection('students');
var cursor = collection.find({});
var next = cursor.next();
while (next) {
next(updateScore);
next = cursor.next();
}
db.close();
});
error
/Users/harrymoreno/programming/mongodb/mongo101ForNode/node_modules/mongodb
/lib/mongodb/mongo_client.js:475
throw err
^
TypeError: Object #<Cursor> has no method 'next'
at /Users/harrymoreno/programming/mongodb/mongo101ForNode/week03/app.js:35:21
at /Users/harrymoreno/programming/mongodb/mongo101ForNode/node_modules/mongodb/lib/mongodb/mongo_client.js:472:11
at process._tickCallback (node.js:419:13)
sample student
{
"_id" : 137,
"name" : "Tamika Schildgen",
"scores" : [
{
"type" : "exam",
"score" : 4.433956226109692
},
{
"type" : "quiz",
"score" : 65.50313785402548
},
{
"type" : "homework",
"score" : 89.5950384993947
}
]
}
UPDATED - v.2
According to the information provided in your last remark abut mongodb package version, I've changed to solution to the one you've improved for specific version compliance (using the 1.4.x node.js mongodb driver) :
var MongoClient = require('mongodb').MongoClient;
var cursor = null,
collection = null,
dbSrc = null;
var removeLowestHWScore = function(scores) {
var lowestHWID = -1;
for(var i=0;i<scores.length; i++) {
if (scores[i].type === 'homework') {
if (lowestHWID === -1) {
lowestHWID = i;
} else if (scores[i].score < scores[lowestHWID].score) {
lowestHWID = i;
}
}
}
// scores.splice(lowestHWID);
if (lowestHWID >= 0)
scores.splice(lowestHWID, 1);
return scores;
};
var callback = function(err, r) {
if (err) throw err;
console.log('updated record');
cursor.nextObject(updateScore);
};
var updateScore = function(err, doc) {
if (err) throw err;
if (doc === null)
return dbSrc.close();
var updatedScores = removeLowestHWScore(doc.scores);
collection.update({_id:doc._id},
{$set: {scores: updatedScores }},
callback);
};
MongoClient.connect('mongodb://localhost:27017/school', function(err, db) {
if(err) throw err;
dbSrc = db;
collection = db.collection('students');
cursor = collection.find({});
cursor.nextObject(updateScore);
});