node.js and mongodb find and delete - node.js

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

Related

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 to scan in dynamoDB based on the values in an array?

here is my code where i have a list of values in an array. I need to fetch all the projects from project table which matches the id's in the array.
var arr=[];
for(var index in data.Items){
if(data.Items[index].hasOwnProperty('projectId'))
arr.push(data.Items[index].projectId);
};
var params = {
TableName: 'projects',
FilterExpression: 'id IN (:id)',
ExpressionAttributeValues: {
':id': arr
}
};
dynamodbclient.scan(params, function (err, docs) {
if (err) {
console.log("Error", err);
} else {
console.log("Success");
callback(err, docs.Items);
}
});
However i am not getting the proper results.
Option 1 - Static :-
If you know all the values its count upfront, please construct the FilterExpression as mentioned below:-
var params = {
TableName : "projects",
FilterExpression : "id IN (:id1, :id2)",
ExpressionAttributeValues : {
":id1" : "id val 1",
":id2" : "id val 2"
}
};
Option 2 - Dynamic:-
var titleValues = ["The Big New Movie 2012", "The Big New Movie"];
var titleObject = {};
var index = 0;
titleValues.forEach(function(value) {
index++;
var titleKey = ":titlevalue"+index;
titleObject[titleKey.toString()] = value;
});
var params = {
TableName : "Movies",
FilterExpression : "title IN ("+Object.keys(titleObject).toString()+ ")",
ExpressionAttributeValues : titleObject
};
docClient.scan(params, onScan);
function onScan(err, data) {
if (err) {
console.error("Unable to scan the table. Error JSON:", JSON.stringify(
err, null, 2));
} else {
// print all the movies
console.log("Scan succeeded.");
data.Items.forEach(function(movie) {
console.log("Item :", JSON.stringify(movie));
});
// continue scanning if we have more movies
if (typeof data.LastEvaluatedKey != "undefined") {
console.log("Scanning for more...");
params.ExclusiveStartKey = data.LastEvaluatedKey;
docClient.scan(params, onScan);
}
}
}

Error in Mongodb with native Node.js Driver

I'm doing a homework exercise, and the following code returns a document of "null" prematurely (before the cursor is exhausted), and crashes the program at the next value since I have already closed the database:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/weather', function(err, db) {
if(err) throw err;
var query = {};
var cursor = db.collection('data').find(query).sort({'State' : 1, Temperature : -1});
var currentState = '';
var lastState = '';
cursor.each(function(err, doc) {
if(err) throw err;
if(doc == null) {
//console.log(doc.State)
return db.close();
}
if(doc != null){
currentState = doc.State;
if(currentState != lastState){
var query2 = {"_id" : doc._id};
doc['month_high'] = true;
db.collection('data').update(query2, doc, function(err,updated){
if(err) throw err;
console.dir("Successfully Updated " + updated + "documents");
});
}
lastState = doc.State;
}
});
});
HOWEVER!! if I limit the batchsize of the cursor to 10 or 20, by changing the one line of code to:
var cursor = db.collection('data').find(query).sort({'State' : 1, Temperature : -1}).batchSize(20);
The code executes perfectly without errors. What's going wrong???

cursor has no method next

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

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