TotalJs loop to insert to database rethinkdb - javascript

I'm trying to get the url for each element, but when it goes to my MODEL query it stays in the first element of the array. Any ideas to solve this?
var loopAndInsert = function(myData) {
for (var i = 0; i < myData.length; i++) {
var prop = myData[i];
MODEL('myModel').query(prop.url, (err, res) => {
if (err) callback(err);
if (res[0].url) {
console.log(res[0].url);
return
} else {
MODEL('myModel').insert(prop, (err, res) => {
if (err) throw err;
else {
console.log('done');
}
});
}
});
}
}

var loopAndInsert = function(myData) {
for (var i = 0; i < myData.length; i++) {
let prop = myData[i];
MODEL('myModel').query({url: prop.url}, (err, res) => {
if (err) callback(err);
if (res.length !== 0) {
console.log('not added already in system');
return
} else {
MODEL('myModel').insert(prop, (err, res) => {
if (err) throw err;
else {
console.log('in db');
}
});
}
});
}
}

Related

How to make the program wait for the if statement to finish before continuing in javascript?

I'm new to Javascript. I want to make this block run after the if statement is finished (asynchronous). The reason I want that is that I want to make some changes to update them if it falls into the if statement
let params = {
TableName: "storepedia-test",
Item: updatedItem
};
docClient.put(params, function (err, data) {
if (err) {
console.log(err);
} else {
res.redirect('/devices');
}
});
Here is my whole code
const { id } = req.params;
const file = req.file;
let updatedItem = { ...req.body};
updatedItem.id = id;
if (file !== undefined){
const deleteParams = {
Key: updatedItem.image,
Bucket: bucketName
}
s3.deleteObject(deleteParams, async (err, data) => {
if (err) {
console.log(err)
} else {
const result = await uploadFile(file);
console.log('result', result);
await unlinkFile(file.path);
updatedItem.image = result.Key;
let params = {
TableName: "storepedia-test",
Item: updatedItem
};
docClient.put(params, function (err, data) {
if (err) {
console.log(err);
} else {
res.redirect('/devices');
}
});
}
})
}
let params = {
TableName: "storepedia-test",
Item: updatedItem
};
docClient.put(params, function (err, data) {
if (err) {
console.log(err);
} else {
res.redirect('/devices');
}
});
Just to run something after the if? I think this is the best spot:
docClient.put(params, function(err, data) {
if (err) {
console.log(err);
} else {
// run async code here.
// when done do the redirect.
// for example:
s3.do_something(function(err, data) {
if (err) {
console.log(err)
} else {
console.log(data)
res.redirect('/devices');
}
})
}
});

How to use the equality operator correctly in Nodejs

I want to get all the flights of the airline_name and destination entred, but I get all flights of all airlines and all destinations not of the specified entries. What should I change in the code so it can work?
function get_flights_by_airline_destination(airline_name, destination, callback) {
let request = require('request');
let url = 'http://api.aviationstack.com/v1/flights?access_key=xxxx&flight_status=scheduled'
request(url, function (err, response, body) {
if (err) {
console.log('error:', error);
callback(err);
} else {
let vol = JSON.parse(body)
result= []
num = vol.pagination.limit
for (let i = 0; i < 10; i++) {
arrival = vol.data[i].arrival.timezone
airline=vol.data[i].airline.name
if ((destination == arrival)&&(airline_name == airline)) {
one_flight = {number: vol.data[i].flight.number, date: vol.data[i].flight_date, departure: vol.data[i].departure.timezone, arrival: vol.data[i].arrival.timezone, from: vol.data[i].departure.airport, to: vol.data[i].arrival.airport, airline: vol.data[i].airline.name}
result.push(one_flight)
}
}
callback(null, result)
}
});
}
function get_flights( req, res) {
get_flights_by_airline_destination( 'air france','europe/rome' ,function( err, result) {
if ( err) {
console.log("error")
}
else {
var links = []
result.map( ( result) => {
links.push(
'from '+' '+result["departure"]+' '+ 'to'+' '+result["arrival"]+' '+'on'+' '+result["airline"],
)
})
console.log(links)
}
})
}
get_flights()

Node js not saving method PUT

I am trying to update object values inside of array. I have done the method and search the element in the array that I want, and returns me 200. But after when I do another request the value return to the original (is not saving).
First of all this is the schema:
{
"_id" : "1",
"username" : "a",
"elements" : [{"_id": "22", "name":"bb"}, {"_id":"33", "name": "cc"}]
}
and this is my method
update = function(req, res) {
User.findById(req.params.id, function (err, user) {
if (!user) {
res.send(404, 'User not found');
}
else{
var array = user.elements;
for (var i = 0; i < array.length; i++) {
if (array[i]._id == "22") {
result = array[i];
if (req.body.name != null) result.name = req.body.name;
result.save(function(err) {
if(!err) {
console.log('Updated');
}
else {
console.log('ERROR: ' + err);
}
res.send(result);
});
break;
}
}
}
});
}
I don't know what I am doing wrong. I mean I simplified everything but I think that the problem is in the method.
You have to save the user object and result just like this :
update = function(req, res) {
User.findById(req.params.id, function (err, user) {
if (!user) {
res.send(404, 'User not found');
}
else{
var array = user.elements;
for (var i = 0; i < array.length; i++) {
if (array[i]._id == "22") {
result = array[i];
if (req.body.name != null) result.name = req.body.name;
break;
}
}
user.save(function(err) {
if(!err) {
console.log('Updated');
}
else {
console.log('ERROR: ' + err);
}
res.send(user);
});
}
});
}

How to perform file write with increment data in node js?

I have a list of 80 items and I get 10 item on each page.Now my idea is to write all the data into file in such a way that first 10 will be in one file and then next 10 in another and so on i get 8 pages for my 80 blogs of 10 in each page.The problem is I am getting only one file got written with 10 blogs what about the else.Can anyone please find the error.Thanks.For that I wrote the script as follows,
I find that the loop is not getting incremented.
exports.getBlogsTest = function(req, res) {
helper.logs('getBlogs', 'blog');
var pages = ['undefined', '2', '3', '4', '5', '6', '7', '8'],
pageNum = '';
pages.forEach(function(i, v) {
try {
var currentPage = Number(i);
var itemsPerPage = 10;
var startItem = (currentPage - 1) * itemsPerPage;
async.waterfall([
function(done) {
try {
if (currentPage === 1) {
blogs.count().exec(function(err, count) {
if (err) {
helper.logs('getBlogs', 'blog', err, 'console');
throw err;
} else {
done(err, count);
}
});
} else {
done('', 'page');
}
} catch (e) {
helper.logs('getBlogs', 'blog', e.message);
}
},
function(count, done) {
try {
if (count) {
if (count && count !== 'page') {
res.setHeader('totalItems', count);
}
blogs.find().sort({ date: -1 }).select('-text').skip(startItem).limit(itemsPerPage).exec(function(err, data) {
if (err) {
helper.logs('getBlogs', 'blog', err, 'console');
throw err;
}
if (data && data.length > 0) {
res.send(data);
console.log('reached###################')
if (i === 'undefined') {
pageNum = '';
} else {
pageNum = i;
}
var fileName = 'public/amp/test2/amp-blog-list' + pageNum + '.html';
var modData = data;
fs.writeFile(fileName, modData, function(err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
} else {
res.send([]);
}
});
} else {
res.send([]);
}
} catch (e) {
helper.logs('getBlogs', 'blog', e.message);
}
}
],
function(err) {
helper.logs('getBlogs', 'blog', err, 'console');
throw err;
});
} catch (e) {
helper.logs('getBlogs', 'blog', e.message);
}
})
};
Why are you using so many try catch?
While it might be useful in many cases you should avoid using it when not necessary.
A few points where you had an issues:
var currentPage = Number(i);
when i is 'undefined' currentPage === NaN
same for var startItem = (currentPage - 1) * itemsPerPage;
when currentPage is 'NaN' startItem === NaN
What i guess is that you thought the params in forEach are (index, value) but it's the other way round (value, index)
I tried to improve your code a bit but haven't actualy run it.
exports.getBlogsTest = function(req, res) {
helper.logs('getBlogs', 'blog');
var itemsPerPage = 10;
for (var i = 1; i < 11; i++) { // pages 1-10
(function(currentPage){ // currentPage = i
var startItem = (currentPage - 1) * itemsPerPage;
async.waterfall([
function(done) {
if (currentPage === 1) {
blogs.count().exec(function(err, count) {
if (err) {
helper.logs('getBlogs', 'blog', err, 'console');
//throw err;
done(err); // the done callback will be called with the error
} else {
done(null, count); // no error so send null
}
});
} else {
done(null, 'page'); // no error so send null
}
},
function(count, done) {
if (count) {
if (count !== 'page') {
res.setHeader('totalItems', count);
}
blogs.find().sort({ date: -1 }).select('-text').skip(startItem).limit(itemsPerPage).exec(function(err, data) {
if (err) {
helper.logs('getBlogs', 'blog', err, 'console');
done(err); // you never called done
//throw err;
}
if (data && data.length > 0) {
res.send(data);
var fileName = 'public/amp/test2/amp-blog-list' + (currentPage === 1 ? '' : currentPage) + '.html';
var modData = data;
fs.writeFile(fileName, modData, function(err) {
if (err) {
done(err);
return console.log(err);
}
console.log("The file was saved!");
done(); // you never called done
});
} else {
res.send([]);
done(); // you never called done
}
});
} else {
res.send([]);
done(); // you never called done
}
}
], function done(err) {
// this is called when waterfall is done or in case of error
// it would always throw if you didn't check for error
// also is it necessary to throw?
// if (err) throw err;
helper.logs('getBlogs', 'blog', err, 'console');
});
})(i);
}
};

cant add more than one object into db using mongoose

I have a function that is supposed to add new item each time there is a match as below:
function getTimeEntriesFromWorksnap(error, response, body) {
//console.log(response.statusCode);
var counter = 1;
if (!error && response.statusCode == 200) {
parser.parseString(body, function (err, results) {
var json_string = JSON.stringify(results.time_entries);
var timeEntries = JSON.parse(json_string);
_.forEach(timeEntries, function (timeEntry) {
_.forEach(timeEntry, function (item) {
Student.findOne({'worksnap.user.user_id': item.user_id[0]})
.populate('user')
.exec(function (err, student) {
if (err) {
throw err;
}
var newTimeEntry = _pushToObject(student.worksnap.timeEntries, item);
student.worksnap.timeEntries = {};
student.worksnap.timeEntries = newTimeEntry;
student.save(function (err) {
if (err) {
//return res.status(400).send({
// message: errorHandler.getErrorMessage(err)
//});
} else {
//res.json(item);
}
});
});
});
});
});
}
}
For some reason it is only inserting once for each student that it finds.
And my Student schema looks like this:
var StudentSchema = new Schema({
firstName: {
type: String,
trim: true,
default: ''
//validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
type: String,
trim: true,
default: ''
//validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
worksnap: {
user: {
type: Object
},
timeEntries: {
type: Object
},
}
});
Any solution?
My Guess is its always pushing the last one... closures...
function getTimeEntriesFromWorksnap(error, response, body) {
//console.log(response.statusCode);
var counter = 1;
if (!error && response.statusCode == 200) {
parser.parseString(body, function (err, results) {
var json_string = JSON.stringify(results.time_entries);
var timeEntries = JSON.parse(json_string);
_.forEach(timeEntries, function (timeEntry) {
_.forEach(timeEntry, function (item) {
saveStudent(item);
});
});
});
}
}
Below is saveStudent function
function saveStudent(item) {
Student.findOne({
'worksnap.user.user_id': item.user_id[0]
})
.populate('user')
.exec(function(err, student) {
if (err) {
throw err;
}
var newTimeEntry = _pushToObject(student.worksnap.timeEntries, item);
student.worksnap.timeEntries = {};
student.worksnap.timeEntries = newTimeEntry;
student.save(function(err) {
if (err) {
//return res.status(400).send({
// message: errorHandler.getErrorMessage(err)
//});
} else {
//res.json(item);
}
});
});
}
OR
wrap it inside a closure...
function getTimeEntriesFromWorksnap(error, response, body) {
//console.log(response.statusCode);
var counter = 1;
if (!error && response.statusCode == 200) {
parser.parseString(body, function(err, results) {
var json_string = JSON.stringify(results.time_entries);
var timeEntries = JSON.parse(json_string);
_.forEach(timeEntries, function(timeEntry) {
_.forEach(timeEntry, function(item) {
(function(item){
Student.findOne({
'worksnap.user.user_id': item.user_id[0]
})
.populate('user')
.exec(function(err, student) {
if (err) {
throw err;
}
var newTimeEntry = _pushToObject(student.worksnap.timeEntries, item);
student.worksnap.timeEntries = {};
student.worksnap.timeEntries = newTimeEntry;
student.save(function(err) {
if (err) {
//return res.status(400).send({
// message: errorHandler.getErrorMessage(err)
//});
} else {
//res.json(item);
}
});
});
}(item))
});
});
});
}
}
Can you use async library and check out...
var async = require('async');
async.map(timeEntries, function (timeEntry, next) {
async.map(timeEntry, function (item, next) {
//your code.
});
});

Categories

Resources