How to process data read from database - javascript

I am processing data read from database on the server using the following code:
module.exports = mongoose.model('Todo', {
text : {type : String, default: ''},
created_at : Date
});
var processTodos = function ( todos ){
for (var i = todos.length - 1; i >= 0; i--) {
// Following update is not happening
todos[i].created_at = "Custom date";
};
console.dir(todos);
return todos;
};
I am not able to figure out how to update this. Is there a syntax issue that is causing this.
I am using MEAN stack for my application.
// Following update is not happening
todos[i].created_at = "Custom date";
What am i missing here.
Here is the console log for "console.dir(todos);":
{ _id: 5489dda3f23f159400475dba,
created_at: Thu Dec 11 2014 23:38:35 GMT+0530 (India Standard Time),
__v: 0,
text: 'Testing sorting at server side' }
{ _id: 5489ddacf23f159400475dbb,
created_at: Thu Dec 11 2014 23:38:44 GMT+0530 (India Standard Time),
__v: 0,
text: 'It works' }
{ _id: 5489f31a12fa54cc127f3e1d,
created_at: Fri Dec 12 2014 01:10:10 GMT+0530 (India Standard Time),
__v: 0,
text: 'time to add more data' }

If you'd like to save the changes you're making to your object, you need to persist the change using the .save() method like so:
var processTodos = function ( todos ){
for (var i = todos.length - 1; i >= 0; i--) {
// Following update is not happening
todos[i].created_at = "Custom date";
todos[i].save();
};
console.dir(todos);
return todos;
};

Related

State Variable not being correctly captured, when passing through components

I have excluded some parts of my original code for readability, sorry if it causes any confusion!
I have a state variable in App.js defined as such
const [tasks, setTasks] = useState([])
From App.js, I pass into Tasks.js the state variable as a
prop.
Tasks.js receives the prop and sorts it as below (when a certain button is clicked)
const Tasks = function ({tasks, setTasks}) {
setTasks(tasks.sort((a, b) => {
if ((moment(a.isoDay).unix()) < (moment(b.isoDay).unix())) return -1
else {
return 0
}
}))
}
This causes the state variable in App.js to be updated, and this state variable is
passed into Calendar.js (from App.js) as a prop as well, as seen below
const Calendar = ({tasks}) => {
function TaskToCalendar(tasks) {
console.log(tasks)
console.log(tasks[0])
}
}
However, I am not accurately capturing the value of tasks.
For example, console.log(tasks) yields this before it is
sorted in Tasks.js
(2) [{…}, {…}]
0: {text: "Test0", day: "Tue Jun 01 2021"}
1: {text: "Test1", day: "Wed Jun 02 2021"}
and yields this after it is sorted in Tasks.js
(2) [{…}, {…}]
0: {text: "Test1", day: "Wed Jun 02 2021}
1: {text: "Test0", day: "Tue Jun 01 2021}
But, console.log(tasks[0]) yields this before and
after it is sorted
{text: "Test0", day: "Tue Jun 01 2021"}
I have to click on another button somewhere in my UI (that runs an unrelated function), for console.log(tasks[0]) to yield {text: "Test1", day: "Wed Jun 02 2021} after sorting.
How would I go about correctly passing the value of tasks, such that accessing the array indices gives me the correct values?
The SetTask function is working asynchronously. hence, this behavior.
For logging the value you can use the useeffect Hook

Mongoose not returning the correct number of results

I'm new to mongoose. I'm trying to query by createdAt date, with startDate and endDate, however I got the incorrect number of results.
data
{"_id":{"$oid":"5f4fab9beceaa20f898feafb"},"message":"Inquiry 101","service":"GENERAL_INQUIRY","name":"Alex","email":"alex#gmail.com","personalNumber":"0991898838398","createdAt":{"$date":"2020-09-02T14:26:35.237Z"},"updatedAt":{"$date":"2020-09-02T14:26:35.237Z"}}
{"_id":{"$oid":"5f4fc3677e7b1e2d806714cf"},"message":"Inquiry 101","service":"GENERAL_INQUIRY","name":"Joshua","email":"joshua#gmail.com","personalNumber":"0991898838398","createdAt":{"$date":"2020-09-02T16:08:07.123Z"},"updatedAt":{"$date":"2020-09-02T16:08:07.123Z"}}
{"_id":{"$oid":"5f50b80f28ca26065b2ac9a5"},"message":"Inquiry 101","service":"GENERAL_INQUIRY","name":"Harold","email":"harold#gmail.com","personalNumber":"0991898838398","createdAt":{"$date":"2020-09-03T09:31:59.112Z"},"updatedAt":{"$date":"2020-09-03T09:31:59.112Z"}}
{"_id":{"$oid":"5f59104ff518c40579b578d0"},"message":"Inquiry 101","service":"GENERAL_INQUIRY","name":"Katy","email":"katy#gmail.com","personalNumber":"0991898838398","createdAt":{"$date":"2020-09-09T17:26:39.787Z"},"updatedAt":{"$date":"2020-09-09T17:26:39.787Z"}}
I have 4 records with the ff. date 2020-09-02, 2020-09-03 and 2020-09-09
I wanted to get all records from 2020-09-02 and 2020-09-03, with these I expected 3 results as I have to records on the 2020-09-02, however I only got 2 results, those records have 2020-09-02 date with them.
const { limit = 30 } = params;
return new Promise((resolve, reject) => {
const query = {
createdAt: {
$gte: '2020-09-02',
$lte: '2020-09-03',
}
};
this.model.find(query).sort({
createdAt: 'descending',
}).limit(limit).exec((err, res) => {
if (!err) {
resolve(res);
}
reject(err);
})
})
Did I miss something with my code?
I also tried passing new Date('2020-09-02') but I still got same results.
I tried setting mongoose debug to true and below is what I got.
Mongoose: inquiries.find({ createdAt: { '$gte': new Date("Wed, 02
Sep 2020 00:00:00 GMT"), '$lte': new Date("Thu, 03 Sep 2020 00:00:00 GMT") }}, { sort: { createdAt: -1 }, limit: 30, projection: {}
})
Thanks in advance.
Youre looking for records greater than 2020-09-02 00:00:00 and less than 2020-09-03 00:00:00.
You only have 2 records which are between these values, if you want records including those at 2020-09-03 23:59:59, set your lte to 2020-09-04

Snapshot shows timezone name instead of GMT code in CI server

I'm using a snapshot test in my project and came across a weird problem when running this specific test on a CI server: it displays the timezone name instead of the GMT code, causing the test failure.
I have tried using "moment-timezone" and Date.UTC() to normalize the dates, the result shown was the correct date with the same issue as above.
I've also tried to stub the global.Date object, but the components complained about prop incompatibility.
it('should render with props', () => {
const order = {
merchant: { logo: 'abc', name: 'Pizza Hut' },
bag: {
items: [{ name: 'Corn & Bacon' }],
total: {
valueWithDiscount: 99.99,
},
},
delivery: {
deliversAt: new Date('2019-05-21 13:00'),
},
payment: {
mode: 'online',
},
lastStatus: API_STATUSES.cancelled,
createdAt: new Date('2019-05-21 12:00'),
details: {},
};
const wrapper = shallowMount(Order, {
...commons,
propsData: { order },
});
expect(wrapper).toMatchSnapshot();
});
See that the expected date is the same as the received one, but syntactic differences:
<div class="order__details">
- <orderdetails-stub paymentmode="online" deliverytime="Fri Jun 21 2019 10:00:00 GMT-0300 (GMT-03:00)" value="99.99" laststatus="cancelled"></orderdetails-stub>
+ <orderdetails-stub paymentmode="online" deliverytime="Fri Jun 21 2019 10:00:00 GMT-0300 (Brasilia Standard Time)" value="99.99" laststatus="cancelled"></orderdetails-stub>
Using Date strings as props like this is hazardous and likely to lead to the sort of problem you're encountering.
Best practice for tests in my experience is to use Date.getTime() so values are numbers of milliseconds without any locale information.
Alternatively, you can use moment-timezone as described in this article:
import moment from 'moment-timezone';
it('renders without crashing', () => {
moment.tz.setDefault('EST');
let props = {
currentDay: moment("2017-09-15 09:30:00").format("MMM Do YYYY h:mm:ss a")
};
const tree = renderer.create(<App {...props} />).toJSON();
expect(tree).toMatchSnapshot();
});

Cannot get attribute size from File object in React

With input is file, I can log to console the File as
console.log(file.size)
It gives me:
File(3987) {name: "download.jpeg", lastModified: 1544914267262, lastModifiedDate: Sat Dec 15 2018 14:51:07 GMT-0800 (Pacific Standard Time), webkitRelativePath: "", size: 3987, …}
lastModified: 1544914267262
lastModifiedDate: Sat Dec 15 2018 14:51:07 GMT-0800 (Pacific Standard Time) {}
name: "download.jpeg"
size: 3987
type: "image/jpeg"
webkitRelativePath: ""
__proto__: File
However when I do console.log(e.target.files[0].size)
It does not even fire.
Full Code as requested. FIle is coming from <input onChange={(e)=>{this.handChangeFile(e.target.files[0])}}/>
this.handleChangeFile = (file) => {
console.log(typeof file)
this.setState({ thefile: file })
let fileData = new FileReader();
fileData.readAsDataURL(file);
fileData.onloadend = () => {
imageBase64 = fileData.result
if (this.state.first == true) {
this.setState({ binary: imageBase64, hide_stock: !this.state.hide_stock, first: false }, () => {
})
}
else
this.setState({ binary: imageBase64 }, () => {
})
}
}
This is my solution on jsfiddle
with jQuery: https://jsfiddle.net/huynhsamha/dqLv83zr/
with React: https://jsfiddle.net/huynhsamha/23fv1te5/
Both they are working. Can you share your code why it is not working?
jQuery
<script async src="//jsfiddle.net/huynhsamha/dqLv83zr/embed/js,html,css,result/dark/"></script>
React
<script async src="//jsfiddle.net/huynhsamha/23fv1te5/embed/js,html,css,result/dark/"></script>

Angularjs send empty JSON to server (ONLY in IE 9 and greater)

I have a little issue with my angularjs script.
I'm trying to post data to server (PHP script which saves values to database).
It works correctly in Chrome, Mozilla, Opera and each other but totally not in IE. I tried IE9, 10 and also 11 (all without add-ons)and still can't figure it out.
In IE my angularjs posts only empty JSON (something like {}).
Here's my angularjs POST script.
$scope.submitForm = function() {
// Posting data to php file
$http({
method : 'POST',
url : 'ajax/newInvoice.php',
data : $scope.invoice, //forms user object
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
getInvoices();
$scope.invoice = {items: [{qty: 1,description: '',cost: 0,taxPerc: 21}],odberatel: '',konecny_prijemce: '',datum_objednavky: new Date(),datum_vystaveni: new Date(),datum_splatnosti: new Date(),datum_zdanitelneho_plneni: new Date(),zpusob_uhrady: 'Platba kartou',dodaci_metoda: 'Osobní odběr'};
});
};
And here's PHP.
<?php
require_once '../includes/db.php'; // The mysql database connection script
$created = date("Y-m-d H:i:s", strtotime("now"));
$query = "SELECT id FROM ang_faktury ORDER BY id DESC";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$last_invoice_id = intval($row["id"]);
$year = date("Y");
$month = date("m");
$idString = str_pad(($last_invoice_id + 1), 5, '0', STR_PAD_LEFT);//id faktury ang_faktury[id], ang_faktury_polozky[id_faktury]
$faCislo = 'OB/'.$year.'/'.$month.'/'.$idString; //cislo faktury ang_faktury[cislo_faktury]
$_POST = json_decode(file_get_contents('php://input'), true);
$dzp = $_POST['datum_zdanitelneho_plneni'];
$datum_zdanitelneho_plneni = substr($dzp, 0, 10);
$dzpForm = date("d.m.Y", strtotime($datum_zdanitelneho_plneni));
$do = $_POST['datum_objednavky'];
$datum_objednavky = substr($do, 0, 10);
$doForm = date("d.m.Y", strtotime($datum_objednavky));
$dv = $_POST['datum_vystaveni'];
$datum_vystaveni = substr($dv, 0, 10);
$dvForm = date("d.m.Y", strtotime($datum_vystaveni));
$ds = $_POST['datum_splatnosti'];
$datum_splatnosti = substr($ds, 0, 10);
$dsForm = date("d.m.Y", strtotime($datum_splatnosti));
foreach($_POST['items'] as $item){
$sumPriceTotal += $item['priceTotal'];
$query2="insert into ang_faktury_polozky (id_faktury,name,cena,ks,dph_proc,dph,total) values('$idString','$item[description]','$item[mjPrice]','$item[qty]','$item[taxPerc]','$item[taxSum]','$item[priceTotal]')";
$mysqli->query($query2);
}
$spt = "{$sumPriceTotal}";
$cbd = (($spt*100)/121);
$dph = $spt - $cbd;
$query3="insert into ang_faktury (id,created_at,cislo_faktury,datum_zdanitelneho_plneni,odberatel,konecny_prijemce,zpusob_uhrady,dodaci_metoda,cislo_objednavky,datum_objednavky,datum_vystaveni,datum_splatnosti,cena_bez_dph,dph,celkem_k_uhrade) values('$idString','$created','$faCislo','$dzpForm','$_POST[odberatel]','$_POST[konecny_prijemce]','$_POST[zpusob_uhrady]','$_POST[dodaci_metoda]','$faCislo','$doForm','$dvForm','$dsForm','$cbd','$dph','$spt')";
$mysqli->query($query3);
mysqli_close($mysqli);
?>
Thanks for any advise.
check your data before sending console.log(data),
and check your data after receiving print_r($_POST) (in myFile.php)
from console (newInvoice.php):
Array
(
[items] => Array
(
[0] => Array
(
[qty] => 1
[description] => MIKI_01
[cost] => 10
[taxPerc] => 21
[priceTotal] => 10.00
[taxSum] => 1.74
[mjPrice] => 8.26
)
[1] => Array
(
[qty] => 1
[description] => MIKI_02
[cost] => 20
[taxPerc] => 21
[priceTotal] => 20.00
[taxSum] => 3.47
[mjPrice] => 16.53
)
)
[odberatel] => MIKI
[konecny_prijemce] =>
[datum_objednavky] => 2016-01-16T13:39:32.554Z
[datum_vystaveni] => 2016-01-16T13:39:32.554Z
[datum_splatnosti] => 2016-01-16T13:39:32.554Z
[datum_zdanitelneho_plneni] => 2016-01-16T13:39:32.554Z
[zpusob_uhrady] => Platba kartou
[dodaci_metoda] => Osobní odběr
)
Console (app.js)
Object {items: Array[2], odberatel: "MIKI", konecny_prijemce: "", datum_objednavky: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time), datum_vystaveni: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)…}
datum_objednavky: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
datum_splatnosti: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
datum_vystaveni: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
datum_zdanitelneho_plneni: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
dodaci_metoda: "Osobní odběr"
items: Array[2]
0: Object
$$hashKey: "object:4"
cost: 10
description: "MIKI_01"
mjPrice: "8.26"
priceTotal: "10.00"
qty: 1
taxPerc: 21
taxSum: "1.74"
__proto__: Object
1: Object
$$hashKey: "object:69"
cost: 20
description: "MIKI_02"
mjPrice: "16.53"
priceTotal: "20.00"
qty: 1
taxPerc: 21
taxSum: "3.47"
__proto__: Object
length: 2
__proto__: Array[0]
konecny_prijemce: ""
odberatel: "MIKI"
zpusob_uhrady: "Platba kartou"
__proto__: Object

Categories