Cannot access an object property in my array map? - javascript

I'm not able to access object's properties from my array.
Here is my code:
{
this.props.viewer.messagesByUser.edges.map(edge => {
console.log("chatFriendPopPup id = ", chatFriendPopPup.id)
console.log("receiver['_id'] = ", edge.node.receiver['_id']) // returns undefined
console.log("receiver._id = ", edge.node.receiver._id) // returns undefined
console.log("receiver._id = ", edge.node.receiver)
if (edge.node.receiver._id.toString() === chatFriendPopPup.id.toString()) {
return <li > {
edge.node.body
} - seen: {
edge.node.seen
} < /li>
}
})
}
Receiver has properties like this, but I cannot get ._id
{
_id: 597 f7eb1e5131d5a50e18d14,
updatedAt: 2017 - 07 - 31 T19: 02: 09.035 Z,
createdAt: 2017 - 07 - 31 T19: 02: 09.035 Z,
fullName: 'ria atayde',
email: 'myloves#gmail.com',
}

Related

Pinia : state change by It self [duplicate]

This question already has answers here:
Javascript date variable assignment
(9 answers)
Closed 10 days ago.
G'day,
I would like to have 3 elements :
Current Date (to display current month)
current date less 1 month (to display the month before)
current date plus 1 month (to display the next month)
I calculate the 2 others months in getter, but when I calc my "lastmonth", it change the selectedMonth value in getter environment :
my code :
import { defineStore } from "pinia";
import type {
agendaState,
} from "#/myApp/interfaces";
export const useAgenda = defineStore("useAgenda", {
state: (): agendaState => ({
selectedMonth: new Date(),
lastMonth: new Date(),
nextMonth: new Date(),
}),
getters: {
lastMonthCalc: (state: agendaState): Date => {
console.log("selectedMonth before : ", state.selectedMonth);
const myDate = state.selectedMonth;
state.lastMonth = myDate;
state.lastMonth = new Date(
state.lastMonth.setMonth(state.lastMonth.getMonth() - 1)
);
console.log("lastMonth after : ", state.lastMonth);
return state.lastMonth;
},
nextMonthCalc: (state: agendaState): Date => {
console.log("selectedMonth before : ", state.selectedMonth);
const theDate = state.selectedMonth;
state.nextMonth = theDate;
state.nextMonth = new Date(
state.nextMonth.setMonth(state.nextMonth.getMonth() + 1)
);
console.log("nextMonth after : ", state.nextMonth);
return state.nextMonth;
},
},
});
The VueJS plugin in chrome display :
My console log looks like (in the chrome console) :
And I would like to have :
selectedMonth = Thu Feb 09 2023 11:05:41 GMT+0100 (heure normale d’Europe centrale),
lastMonth: Mon Jan 09 2023 11:05:41 GMT+0100 (heure normale d’Europe centrale),
nextMonth: Thu Mar 09 2023 11:05:41 GMT+0100 (heure normale d’Europe centrale),
Do you know why ? What is my mistake ?
I try a lot of things but nothing workss.
I find the solution .... the good code is this one :
import { defineStore } from "pinia";
import type {
agendaState,
} from "#/interfaces";
export const useAgenda = defineStore("useAgenda", {
state: (): agendaState => ({
selectedMonth: new Date(),
}),
getters: {
lastMonth: (state: agendaState): Date => {
const myDate = new Date(state.selectedMonth);
new Date(
myDate.setMonth(myDate.getMonth() - 1)
);
return myDate;
},
nextMonth: (state: agendaState): Date => {
const theDate = new Date(state.selectedMonth);
new Date(
theDate.setMonth(theDate.getMonth() + 1)
);
return theDate;
},
},
});
Thanks to my cat to show me what is the point so I change the code for this last version !!!!

How to get the date between the from date and to date?

I'm working on DayPicker to get all the range dates, but I couldn't have any good idea of knowing the dates between the start date and end date.
import { DateRange, DayPicker } from 'react-day-picker'
const [range, setRange] = useState<DateRange | undefined>()
useEffect(() => {
if(range && range.from && range.to) {
console.log('range.from', range.from)
console.log('range.to', range.to)
// range.from Mon Aug 01 2022 00:00:00 GMT-0700 (Pacific Daylight Time)
// range.to Sat Aug 06 2022 00:00:00 GMT-0700 (Pacific Daylight Time)
// I want get 8/1, 8/2, 8/3, 8/4, 8/5 as string data
}
}, [range])
return (
<DayPicker
mode="range"
defaultMonth={new Date()}
selected={range}
onSelect={setRange}
/>
)
Use date-fns and create a function.
const getDatesInRange = (startDate: Date, numberOfDays: number) => {
const dates: Date[] = [];
[...Array(numberOfDays + 1)].forEach((_, i) => {
dates.push(addDays(startDate, i));
});
console.log(dates); // For debugging purposes
return dates;
};
Add an array state const [dateRangeArray, setDateRangeArray] = useState<Date[]>(); and and we update the useEffect.
Here is the full code:
import { addDays, differenceInDays } from 'date-fns';
// inside the component
const [range, setRange] = useState<DateRange | undefined>();
const [dateRangeArray, setDateRangeArray] = useState<Date[]>();
const getDatesInRange = (startDate: Date, numberOfDays: number) => {
const dates: Date[] = [];
[...Array(numberOfDays + 1)].forEach((_, i) => {
dates.push(addDays(startDate, i));
});
console.log(dates); // For debugging purposes
return dates;
};
useEffect(() => {
if (range && range.to && range.from && dateRangeArray === undefined) {
let daysDiff = differenceInDays(range.to, range?.from);
setDateRangeArray(getDatesInRange(range.from, daysDiff));
}
if (range && range.from && range.to) {
console.log('range.from', range.from);
console.log('range.to', range.to);
// range.from Mon Aug 01 2022 00:00:00 GMT-0700 (Pacific Daylight Time)
// range.to Sat Aug 06 2022 00:00:00 GMT-0700 (Pacific Daylight Time)
// I want get 8/1, 8/2, 8/3, 8/4, 8/5 as string data
}
}, [range]);
return (
<div>
<DayPicker mode='range' defaultMonth={new Date()} selected={range} onSelect={setRange} />
</div>
);

Moment giving wrong result when comparing dates

I am attempting to compare 2 dates and I am getting an error.
These are my functions:
const validateDate = (date: string): Moment => {
return moment(`${moment().year()}/${date}`);
};
export const themes: Theme[] = [{
siteCode: '',
costCenter: '',
theme: 'spring',
bannerImage: 'spring.jpg',
cssOverride: 'springThemeStyles.scss',
endDate: moment(validateDate('6/19')).toDate(),
startDate: moment(validateDate('3/20')).toDate()
}];
export const getActiveTheme = (): any => {
const now = moment().toDate();
console.log(now); // Thu Mar 19 2020 21:56:10 GMT-0600 (Central Standard Time)
console.log(themes[0].startDate); // Fri Mar 20 2020 00:00:00 GMT-0600 (Central Standard Time)
console.log(themes[0].startDate >= now); // true
return themes.map((t: Theme) => {
if (t.startDate >= now) { // this is always true I don't know why
if (t.theme.toLowerCase() === 'spring') {
return require('../../../styles/spring.theme.scss');
}
return null;
}
});
};
I don't get why the condition if (t.startDate >= now) {...} is always true.
Any thoughts?
It is simply because startDate is on the Fri Mar 20 2020 and now is on the Thu Mar 19 2020 so it's clear that startDate >= now should be true
Since you have set your startDate to the 20th, startDate >= now would be false when now would be on 21th

How to get a record within a date range in mongodb?

In my mongodb collection I have a record with:
//mongodb field: "birth_date": "1983-05-06T16:26:32.613Z"
And here my find query, to get that record in the range:
var birthYear = 1983;
var birthDateStart = new Date('1.1.' + birthYear); //Sat Jan 01 1983 00:00:00 GMT+0100 (Mitteleuropäische Zeit)
var birthDateEnd = new Date('12.30.' + birthYear); //Fri Dec 30 1983 00:00:00 GMT+0100 (Mitteleuropäische Zeit)
var cursor = db.collection('users').find({
birth_date: {$gte: birthDateStart, $lt: birthDateEnd}
})
I think the problem is the date format, how can I get the same Date() format as that in the database?
I used variety to get the DB schema:
+--------------------------------------------------+
| key | types | occurrences | percents |
| ------------ | -------- | ----------- | -------- |
| _id | ObjectId | 1 | 100.0 |
| bio | String | 1 | 100.0 |
| birth_date | String | 1 | 100.0 |
+--------------------------------------------------+
I use the 'mongodb' package for express.js - and can't use ISODate().
ReferenceError: ISODate is not defined
Thank you for all your hints. The problem was, that the birth_date field was saved as String.
I want to show you in this answer how to change the format of a field from String to Date in all records in your collection and then how to search by Age (in years) when you have saved only the birthdate. Maybe it helps someone else.
Change the String format to Date of the field birth_date:
mongo.connect(url, function (err, db) {
console.log(err);
var resultArray = [];
var cursor = db.collection('users').find({});
cursor.forEach(function (doc, err) {
console.log(doc);
db.collection('users').update({_id: doc._id}, {$set: {birth_date: new Date(doc.birth_date)}});
}, function () {
db.close();
res.send("Done!");
})
})
Find a user who is 18years old:
var search_age = 18;
var birthYear = new Date(Date.now()).getFullYear() - search_age;
var birthDateStart = new Date(birthYear, 0, 1);
var birthDateEnd = new Date(birthYear, 11, 31, 23, 59, 59, 999);
var resultArray = [];
mongo.connect(url, function (err, db) {
console.log(err);
var resultArray = [];
var cursor = db.collection('users').find({
birth_date: {$gte: birthDateStart, $lt: birthDateEnd},
})
;
cursor.forEach(function (doc, err) {
resultArray.push(doc);
}, function () {
db.close();
res.send(resultArray);
})
})

Sequelize: updating updatedAt manually

Below is the code I am using in Hooks to update the updatedAt column for two objects:
hooks: {
afterUpdate: (group, options, callback) => {
console.log("groudId " + groupId + " options " + options)
},
afterCreate: (member, options, callback) => {
return new Promise((resolve, reject) => {
sequelize.models.Group.findOne({
where: {
id: member.group_id
}
}).then((group) => {
if (group) {
var date = new Date();
console.log("BEFORE group.updatedAt " + group.updatedAt)
group.dataValues.updatedAt = new Date()
console.log("CHANGED group.updatedAt " + group.updatedAt)
group.save().then((Group) => {
if (Group) {
console.log("UPDATED Group.updatedAt " + Group.updatedAt)
console.log("UPDATED group.updatedAt " + group.updatedAt)
resolve(Group)
} else {
console.log("NO GROUP Found")
return reject(group.id)
}
}).catch((error) => {
return (error)
})
} else {
return reject(id)
}
}).catch((error) => {
return (reject)
})
})
}
Console Log:
BEFORE group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST)
CHANGED group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST)
UPDATED Group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST)
UPDATED group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST)
BEFORE group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST)
CHANGED group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST)
UPDATED Group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST)
UPDATED group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST)
While the log, what I think, appears correct, why isn't the actual object in the DB updated to the new updatedAt value? Or is there an easier way to update an objects updatedAt column?
This worked for me
group.changed('updatedAt', true)
await group.update({
updatedAt: new Date()
})
Calling just update with updatedAt = new Date is not enough, you must flag column as changed
The following worked for:
group.changed('updatedAt', true)
This will mark the updatedAt column as dirty so it will be updated.
None of the above worked for me, so I had to use model method instead:
await MyModel.update({ updatedAt }, { where: { id: instance.id }, silent: true });
Accodrding to the docs, you can update an instance value by calling instance.set(key, value, [options]), so, in your case it should be:
console.log("BEFORE group.updatedAt " + group.updatedAt)
group.set('updatedAt', new Date())
console.log("CHANGED group.updatedAt " + group.updatedAt)
group.save().then((Group) => { /* the other part of your code*/ })
I was able to update the updatedAt property on a model instance with the .changed() method. This only works if you set two property instances to changed = true
group.changed('updatedAt', true)
group.changed('exampleProperty', true)
await group.save({ silent: false })
it's work
sequelize.getQueryInterface().queryGenerator.updateQuery(
'YOU_TABLE',
{ updated_at: sequelize.literal('CURRENT_TIMESTAMP') },
{ id: 1 },
{ returning: false },
)
sequelize.query(query)
The only thing that worked for me:
await sequelize.query("UPDATE groups SET updatedAt = :date WHERE id = :id", {
replacements: { date: new Date(2012, 7, 22, 2, 30, 0, 0), id: group.id },
});
I made a few small changes to Alexander Zinchuk's code and it works for me:
await MyModel.update({ updatedAt: new Date() }, { where: { id: instance.id }})

Categories