Object.assign not working as expected
Mongoose documents (model instances) are special: they will only print properties that are present in the schema.
If properties aren't defined there, they won't show up when you console.log()
them (and also not if you convert the document to a plain JS object with obj.toObject()
).
This means that using Object.assign()
will only work if you assign properties that are also present in the schema. Any properties that aren't declared will not be shown (nor saved to the database).
If your intention is to use the document for output, you should convert it to a proper JS object first before assigning to it:
let data = Object.assign(booking.toObject(), {
hiw : event.hiw[booking.locale],
tip : event.tip[booking.locale],
start : moment(event.start).format('L')
});
Admin
Updated on August 09, 2022Comments
-
Admin over 1 year
I have one object called bookings, and inside it I have several properties, and i want extend with Object.assign, like this:
let data = Object.assign(booking, { hiw: event.hiw[booking.locale], tip: event.tip[booking.locale], start: moment(event.start).format('L') });
But when I print the data, the result will be the same object from the source (booking), so
hiw
,tip
andstart
will be ignored, but... if I try to do:let data = Object.assign({}, { hiw: event.hiw[booking.locale], tip: event.tip[booking.locale], start: moment(event.start).format('L') });
This will work perfect.
My question is: what am I doing wrong here? Why can't I extend
booking
and I can extend the empty object?That's definitely not a problem with async code, when i try to extend booking, he already exist with all properties inside.
I also was trying to use underscore
extend
method, and the behavior is exactly the same.