I want to update the current date in yyy-mm-dd form so i can query it later but i m unable to insert date in the required format.here what i had did till
const sampleSchema = new mongoose.Schema({
username:String,
date:{
type:Date
}
});
const Sample = new mongoose.model("Sample", sampleSchema);
let currentDate=new Date
const sample = new Sample({
username:req.body.username,
date:currentDate.toISOString().split("T")[0]
});
sample.save()
I'm getting this
{
"_id": {
"$oid": "61b5862c6ff7ff297ae97d0c"
},
"user": "username",
"date": {
"$date": "2021-12-12T00:00:00.000Z"
},
"__v": 0
}
I want date in yyy-mm-dd format.
Use moment.js to convert the ISO formatted date into normal formatted date YYYY-MM-DD Don't try to store your own formate of date on MongoDB because it creates problems in querying data based on date and time. So update it into ISO and then convert it into different formate at the backend
Converting ISO formate Date into YYYY MM DD
date = new Date('2013-08-03T02:00:00Z');
date = moment(date).format('YYYY MM DD'); //result 2013 08 03
Converting YYYY MM DD formate into IOS formate
date = new Date('2013-08-03');
date = moment(date).format();
Another thing users can do is to store data in the form of a string
and use $gt, $gte, $lte and $lt operators for queries
I think I'm going crazy... I'm just trying to do some basic API learning for NodeJS and I've got this, which works fine and prints "United States Dollar" to console...
app.get("/", function(req, res){
const url = "https://api.coindesk.com/v1/bpi/currentprice.json"
https.get(url, function(response){
console.log(response.statusCode);
response.on("data", function(data){
const priceData = JSON.parse(data);
console.log(priceData.bpi.USD.description);
})
})
but when I'm trying to access it by using the array position of USD (which is [0])like this...
app.get("/", function(req, res){
const url = "https://api.coindesk.com/v1/bpi/currentprice.json"
https.get(url, function(response){
console.log(response.statusCode);
response.on("data", function(data){
const priceData = JSON.parse(data);
console.log(priceData.bpi[0].description);
})
})
I get a crash of ...
TypeError: Cannot read property 'description' of undefined
The JSON is
{
"time": {
"updated": "Oct 21, 2021 16:10:00 UTC",
"updatedISO": "2021-10-21T16:10:00+00:00",
"updateduk": "Oct 21, 2021 at 17:10 BST"
},
"disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
"chartName": "Bitcoin",
"bpi": {
"USD": {
"code": "USD",
"symbol": "$",
"rate": "63,222.0050",
"description": "United States Dollar",
"rate_float": 63222.005
},
"GBP": {
"code": "GBP",
"symbol": "£",
"rate": "45,779.4964",
"description": "British Pound Sterling",
"rate_float": 45779.4964
},
"EUR": {
"code": "EUR",
"symbol": "€",
"rate": "54,306.7540",
"description": "Euro",
"rate_float": 54306.754
}
}
}
The USD object is position[0] of the bpi array (right?) so why can't I just tap into it like above? This example seems pretty similar to mine so can't see where I'm going wrong?
The problem is the content of priceData.bpi is not an array [], it's an object {}, so you can't access USD by position, the only way to access it is priceData.bpi.USD.
More about JS arrays, objects.
However, if you really need to access it by position, you can convert the contents of priceData.bpi into an array using the Object.entries() method.
Example
let priceData = {"time":{"updated":"Oct 21, 2021 16:39:00 UTC","updatedISO":"2021-10-21T16:39:00+00:00","updateduk":"Oct 21, 2021 at 17:39 BST"},"disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org","chartName":"Bitcoin","bpi":{"USD":{"code":"USD","symbol":"$","rate":"63,340.4233","description":"United States Dollar","rate_float":63340.4233},"GBP":{"code":"GBP","symbol":"£","rate":"45,865.2439","description":"British Pound Sterling","rate_float":45865.2439},"EUR":{"code":"EUR","symbol":"€","rate":"54,408.4735","description":"Euro","rate_float":54408.4735}}}
let bpiArr = Object.entries(priceData.bpi)
console.log(bpiArr[0][1].description)
Note: the first [0] element of bpiArr[0] contains the string "USD" and the second [1] contains an object which got the description key and its value.
More information
bpi is not an Array but an object. If it uses curly brackets it is an object. If using square brackets it is an array. To access the USD property of bpi object you use dot notation (like you have done: bpi.USD) or you use bpi["USD"]
Based on your JSON bpi is an object but you are accessing it via array index which is wrong. If you want the value of USD, the way you were accessing in the first snippet is correct. However, if you want to use it as an array, you can do like below:
const {bpi= {}} = json;
const bpiArr = Object.entries(bpi);
// to access all the values
for (const [key,val] of bpiArr) {
console.log(key,val.description)
}
I want to ask how can I make my req.query only accepts date format like this YYYY-MM-DD and not just random number because my code still accepting numbers like "123456" in query.
You can try this code below:
const isValidDate = !(new Date('2021/01/20').toString().toLowerCase().includes('invalid'));
if (isValidDate) {
console.log('Valid Date');
} else {
console.log('InValid Date');
}
I'm trying to get records with a date between two dates (provided by URL). A am using Lodash and Moment. I tried it in the following way but the result is empty. Does somebody have any idea? Thank you.
app.get('/paymentListByDate/:from/:to/', (req, res) => {
let response = getDataPayment();
let from_url = req.params.from;
let to_url = req.params.to;
let dateFormat = "DD-MM-YYYY";
let filtered = _.filter(response, { 'dueDate': moment().isBetween(moment(from_url, dateFormat), moment(to_url, dateFormat))});
sendDelayedResponse(res, filtered, 1);
});
sendDelayedResponse() method should be fine. Parameters as well. JSON object is the following:
{
"value": {"amount": 1000, "currency": "CZK"},
"partyAccount": {"prefix": "035", "accountNumber": "123456789", "bankCode" :"2010"},
"dueDate": "15.01.2020",
"recurringPayment": {"firstPayment": "First payment", "lastPayment": "Last payment", "interval": "WEEK"},
"payeeMessage": "Message2",
"payerMessage": "Message1",
"categoryId": 0,
"additionalInfo": {"constantSymbol": "123456789", "variableSymbol": "123456789", "specificSymbol": "123456789"},
"id": 1,
"accountId": 123456789,
"editableByUser": true,
"realizationStatus": "RTS_REALISED"
}
moment() returns current date time. You have to compare from_url with to_url (I don't know why you use _url instead of _date).
filter just working with a collection, I hope getDataPayment() returns a array in any cases.
Without lodash:
const filtered = response.filter((o) => {
return moment(o.dueDate, 'DD.MM.YYYY') // Convert to moment with exactly date format
.isBetween(moment(from_url, dateFormat), moment(to_url, dateFormat));
});
with lodash:
const filtered = _.filter(response, (o) => {
return moment(o.dueDate, 'DD.MM.YYYY')
.isBetween(moment(from_url, dateFormat), moment(to_url, dateFormat));
});
I'm using the latest version of elasticsearch npm with elasticsearch version 6.4 and trying to put new script.
According to thier documentation; putScript function takes id and body properties.
So when i try to call it, for instance:
client.putScript({
id: 'date_formatter',
body: {
lang: "painless",
source: `// Get each field value as string
String datetime = doc[params.field].value.toString();
// Create format object based on string
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(params.format);
// cast datetime into ZonedDateTime to use format function
ZonedDateTime zdt = ZonedDateTime.parse(datetime);
// return formatted date
return zdt.format(formatter);`
}
})
It returns { acknowledged: true } as expected, But when i check it through kibana, it returns:
{
"_id": "date_formatter",
"found": true,
"script": {
"lang": "mustache",
"source": """{"lang":"painless"}"""
}
}
Is there any way to put script into elasticsearch through node client?
You need to wrap both lang and source into a script section basically the same way as described here:
client.putScript({
id: 'date_formatter',
body: {
script: {
lang: "painless",
source: `// Get each field value as string
String datetime = doc[params.field].value.toString();
// Create format object based on string
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(params.format);
// cast datetime into ZonedDateTime to use format function
ZonedDateTime zdt = ZonedDateTime.parse(datetime);
// return formatted date
return zdt.format(formatter);`
}
}
})