cursor has no method next - node.js

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);
});

Related

Error: NJS-012: encountered invalid bind data type in parameter 2

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 ?

Node.js MongoDB insertion takes too much time

I have a certain loop where I'm inserting documents in a MongoDB collection.But only the last document is inserted,may be,the loop is too fast for the insertion.
How can I make the loop wait for the completion of the insertion?
Here is my code:
mongo.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
for (var i = 0; i < totalEmployee; i++) {
var some = array_data[index].split(":");
var thing = some[1].split("\"");
var EID = thing[1];
var Info = [];
index++;
for (var j = 0; j < 2; j++) {
var some = array_data[index].split(":");
var thing = some[1].split("\"");
var first = thing[1];
thing = some[2].split("\"");
var second = thing[0];
Info[j] = first + ":" + second;
index++;
}
console.log(Info);
var unique = date + EID;
dbo.collection("Attendance").find({_id: unique}).toArray(function (err, result) {
if (!result.length) {
dbo.collection("Attendance").insertOne({
_id: unique,
Date: date,
EID: EID,
InTime: Info[0],
OutTime: Info[1]
},function(err, res) {
if (err) throw err;
console.log("1 document inserted");
inserted=false;
}
);
}
else {
console.log(unique+date+EID+Info[0]);
var myquery = {_id: unique};
var newvalues = {$set: {Date: date, EID: EID, InTime: Info[0], OutTime: Info[1]}};
dbo.collection("Attendance").updateOne(myquery, newvalues, function (err, res) {
if (err) throw err;
console.log("1 document updated");
inserted=false;
});
}
}
}
});

How can I use session token for repetitive calls of GEOTAB apis in node js wrapper?

I am using GEOTAB apis to sync vehicle data to my DB.In my software user can register and add geotab account to sync.for sync purpose i have used node js wrapper.With 3 minutes delay this process calls regularly.
I am getting the error "Global login limit exceeded"
var syncUsers = function () {
var i;
async.forEach(geotabUsers, function (geoUser, callback) {
//get index
i = geotabUsers.indexOf(geoUser);
if (apiInstanse[geotabUsers[i].userId] === undefined)
{
apiInstanse[geotabUsers[i].userId] = new API(geotabUsers[i].apiUsername, geotabUsers[i].apiPassword, geotabUsers[i].apiDatabase, js_lang.GEOTAB_SERVER);
}
//sync status data
syncStatusData(apiInstanse[geotabUsers[i].userId], i, userInfo[geotabUsers[i].userId].statusDataFromVersion, geotabUsers[i].userId, userInfo[geotabUsers[i].userId].currentCompany, geotabUsers[i].apiUsername, geotabUsers[i].apiPassword, geotabUsers[i].apiDatabase, userInfo[geotabUsers[i].userId].currentPressureUnit, userInfo[geotabUsers[i].userId].currentDateFormat, userInfo[geotabUsers[i].userId].currentTimeFormat, userInfo[geotabUsers[i].userId].currentTemperatureUnit);
//sync fault data
syncFaultData(apiInstanse[geotabUsers[i].userId], i, userInfo[geotabUsers[i].userId].faultDataFromVersion, geotabUsers[i].userId, userInfo[geotabUsers[i].userId].currentCompany, geotabUsers[i].apiUsername, geotabUsers[i].apiPassword, geotabUsers[i].apiDatabase,function(){
callback();
});
},function(err){
if(err)
{
console.log('done errro:',err);
}
console.log('sync done');
continueSync();
});
Function to sync status data:
var syncStatusData = function (api, i, fromVersion, userId, currentCompany, apiUsername, apiPassword, apiDatabase, currentPressureUnit, currentDateFormat, currentTimeFormat, currentTemperatureUnits)
{
try {
api.call(js_lang.GEOTAB_GETFEED_METHOD, {
typeName: js_lang.GEOTAB_STATUS_DATA,
resultsLimit: js_lang.GEOTAB_API_LIMIT,
fromVersion: fromVersion
}, function (err, data) {
if (err) {
console.log('api Call Error:', userId);
console.log('apiUsername:', apiUsername);
console.log('apiPassword:', apiPassword);
console.log('apiDatabase:', apiDatabase);
console.log('Error', err);
//apiInstanse[userId] = new API(apiUsername, apiPassword, apiDatabase, js_lang.GEOTAB_SERVER);
//throw err;
}
else {
var insertStatus = [];
var sql = "INSERT INTO " + js_lang.TABLE_STATUS_DATA + " (companyId,dateTime,deviceId ,diagnosticId,value,version,uniqueId,userId,unitOfMeasure ) VALUES ?";
//iterate data
if (data.data !== undefined)
{
for (var key in data.data) {
if (diagnosticList[data.data[key].diagnostic.id] === undefined)
{
continue;
}
var normalDate = FUNCTION_CLASS.getNormalDateFromUTC(data.data[key].dateTime);
//prepare data to insert
var insertRow = [
currentCompany,
normalDate,
data.data[key].device.id,
data.data[key].diagnostic.id,
data.data[key].data,
data.data[key].version,
data.data[key].id,
userId,
diagnosticList[data.data[key].diagnostic.id].unitOfMeasure
];
insertStatus.push(insertRow);
}
}
if (insertStatus.length > 0)
{
connection.query(sql, [insertStatus], function (err) {
if (err)
{
throw err;
}
// console.log('toversion:', data.toVersion);
console.log('insert:userId:', userId);
connection.query('UPDATE ' + js_lang.TABLE_USER + ' SET statusDataFromVersion = ? WHERE id = ?',
[data.toVersion, userId]);
});
}
else {
console.log('update user:', userId);
connection.query('UPDATE ' + js_lang.TABLE_USER + ' SET statusDataFromVersion = ? WHERE id = ?',
[data.toVersion, userId]);
}
}
if ((geotabUsers.length - 1) === i)
{
console.log('loop ended');
syncStatusDone = 1;
// continueSync();
}
});
}
catch (e) {
continueSync();
}
}
Function to sync Fault data:
var syncFaultData = function (api, i, fromVersion, userId, currentCompany, apiUsername, apiPassword, apiDatabase,callback)
{
try {
api.call(js_lang.GEOTAB_GETFEED_METHOD, {
typeName: js_lang.GEOTAB_FAULT_DATA,
resultsLimit: js_lang.GEOTAB_API_LIMIT,
fromVersion: fromVersion
}, function (err, data) {
if (err) {
console.log('api faultData Call Error:', userId);
console.log('apiUsername:', apiUsername);
console.log('apiPassword:', apiPassword);
console.log('apiDatabase:', apiDatabase);
console.log('Error', err);
//apiInstanse[userId] = new API(apiUsername, apiPassword, apiDatabase, js_lang.GEOTAB_SERVER);
//throw err;
}
else {
var insertStatus = [];
var sql = "INSERT INTO " + js_lang.TABLE_FAULT_DATA + " (amberWarningLamp,controllerId,count,dateTime,deviceId ,diagnosticId,dismissDateTime,dismissUser,failureModeId,faultLampState,faultState,flashCode,uniqueId,malfunctionLamp,protectWarningLamp,redStopLamp,version,companyId,userId,deleted) VALUES ?";
//iterate data
if (data.data !== undefined)
{
for (var key in data.data) {
if (diagnosticList[data.data[key].diagnostic.id] == undefined)
{
continue;
}
var normalDate = FUNCTION_CLASS.getNormalDateFromUTC(data.data[key].dateTime);
var thisDate = moment(new Date(data.data[key].dateTime)).tz(js_lang.TIMEZONE).format(js_lang.DATETIME_FORMAT);
var thisDayDate = moment(new Date(data.data[key].dateTime)).tz(js_lang.TIMEZONE).format(js_lang.DATE_FORMAT);
var controllerId = '';
if (data.data[key].controller !== undefined && data.data[key].controller.id !== undefined)
{
controllerId = data.data[key].controller.id;
}
else if (data.data[key].controller !== undefined)
{
controllerId = data.data[key].controller;
}
var faultcount = null;
if (data.data[key].count !== undefined)
{
faultcount = parseInt(data.data[key].count);
}
var dismissDateTime = '';
if (data.data[key].dismissDateTime !== undefined)
{
dismissDateTime = moment(new Date(data.data[key].dismissDateTime)).tz(js_lang.TIMEZONE).format(js_lang.DATETIME_FORMAT);
}
var dismissUser = '';
if (data.data[key].dismissUser !== undefined)
{
dismissUser = data.data[key].dismissUser;
}
var failureModeId = '';
if (data.data[key].failureModeId !== undefined && data.data[key].failureModeId.id !== undefined)
{
failureModeId = data.data[key].failureModeId.id;
}
var faultLampState = '';
if (data.data[key].faultLampState !== undefined)
{
faultLampState = data.data[key].faultLampState;
}
var faultState = data.data[key].faultState;
var flashCode = '';
if (data.data[key].flashCode !== undefined)
{
flashCode = data.data[key].flashCode;
}
var malfunctionLamp = data.data[key].malfunctionLamp;
var protectWarningLamp = data.data[key].protectWarningLamp;
var redStopLamp = data.data[key].redStopLamp;
var version = '';
if (data.data[key].version !== undefined)
{
version = data.data[key].version;
}
//prepare data to insert
var insertRow = [
data.data[key].amberWarningLamp,
controllerId,
faultcount,
normalDate,
data.data[key].device.id,
data.data[key].diagnostic.id,
dismissDateTime,
dismissUser,
failureModeId,
faultLampState,
faultState,
flashCode,
data.data[key].id,
malfunctionLamp,
protectWarningLamp,
redStopLamp,
version,
currentCompany,
userId,
0
];
insertStatus.push(insertRow);
}
}
// console.log(insertStatus);
if (insertStatus.length > 0)
{
connection.query(sql, [insertStatus], function (err) {
if (err)
{
throw err;
}
// console.log('toversion:', data.toVersion);
console.log('insert faultData:userId:', userId);
connection.query('UPDATE ' + js_lang.TABLE_USER + ' SET faultDataFromVersion = ? WHERE id = ?',
[data.toVersion, userId]);
callback();
});
}
else {
console.log('update faultData user:', userId);
//test code
//sendEmail(['ankkubosstest#gmail.com','webdeveloper#gmail.com'], 'emailSubject', 'emailText', '<div>html code<div>');
connection.query('UPDATE ' + js_lang.TABLE_USER + ' SET faultDataFromVersion = ? WHERE id = ?',
[data.toVersion, userId]);
callback();
}
}
if ((geotabUsers.length - 1) === i)
{
console.log('loop ended');
syncFaultDone = 1;
}
});
}
catch (e) {
continueSync();
}
}

node.js and mongodb find and delete

hey guys im new to programming in general and i am trying to write a query in node.js to display the lowest score in my database then later on delete it. my data looks like this
{
"_id" : 19,
"name" : "Gisela Levin",
"scores" : [
{
"type" : "exam",
"score" : 44.51211101958831
},
{
"type" : "quiz",
"score" : 0.6578497966368002
},
{
"type" : "homework",
"score" : 93.36341655949683
},
{
"type" : "homework",
"score" : 49.43132782777443
}
]
}
so i need to find and delete just the lowest homework alone and not both. in the code i wrote i am trying to just display these lowest first then i will remove them. so far this code i have written shows both scores like this
'Verdell Sowinski scored 69.09840625499065'
'Verdell Sowinski scored 17.90304994248164'
'Vina Matsunaga scored 19.16579262350994'
'Vina Matsunaga scored 8.217818112853726'
'Vinnie Auerbach scored 23.91300715707971'
'Vinnie Auerbach scored 53.31631231243156'
'Whitley Fears scored 92.2308421188758'
'Whitley Fears scored 97.95928979563497'
'Wilburn Spiess scored 10.53058536508186'
'Wilburn Spiess scored 28.10477578379966'
'Zachary Langlais scored 19.21886443577987'
'Zachary Langlais scored 8.548735651522431'
'aimee Zank scored 6.676176060654615'
'aimee Zank scored 18.52035674134503'
this is what i have so far :
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/school', function(err, db){
if(err) throw err;
var cursor = db.collection('students').find().sort({name : 1});
var list = [];
var count = 0;
var currentName = '';
cursor.each(function(err, doc){
if(err) throw err;
if(doc == null){
return
}
var lowestScore = 1000;
var lowestScore_position = '';
for(i=0; i<doc.scores.length; i++){
if (doc.scores[i].type == 'homework' && doc.scores[i].score<=lowestScore) {
lowestScore = doc.scores[i].score;
lowestScore_position = i;
}
}
console.dir(doc.name + " scored " + lowestScore);
});
});
thanks in advance
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/school', function(err, db) {
if (err) throw err;
var cursor = db.collection('students').find();
var lastStudent = '';
cursor.each(function(err, doc){
if (err) throw err;
if (doc == null) {
setTimeout(function() {
return db.close()
}, 2000);
} else {
var lowScoreIndex = -1;
var lowScore = 100;
Array.prototype.forEach.call(doc.scores, function(score) {
if (score.type === 'homework') {
if (score.score < lowScore) {
lowScore = score.score;
lowScoreIndex = Array.prototype.indexOf.call(score, lowScore);
}
}
});
doc.scores.splice(lowScoreIndex, 1);
db.collection('students').update({'_id':doc['_id']}, doc, function(err, updated) {
if (err) throw err;
})
}
});
});

Need help to write mysql update query in node.js with callback

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});
}
}
);
});

Resources