user1772306
user1772306

Reputation: 469

Can't override property of an JavaScript object

I got a method that is formatting the date property of a message. A user has an array of messages.

user.messages[i].date = formatDate(user.messages[i].date);

// logs the correctly formatted date
console.log(formatDate(user.messages[i].date));

// logs the unformatted date 
console.log(user.messages[i].date); 



However, when I do it like the following code snippet it works.

        user.messages[i] = {
            name: user.messages[i].name,
            body: user.messages[i].body,
            _id: user.messages[i]._id,
            date: formatDate(user.messages[i].date)
        };

Upvotes: 2

Views: 1259

Answers (2)

sidonaldson
sidonaldson

Reputation: 25284

This is a guess but you could add formatteddate:"" into your user model (or similar) and then try:

user.messages[i].formatteddate = formatDate(user.messages[i].date);

Therefore you are not re-configuring it.

Upvotes: 0

user1772306
user1772306

Reputation: 469

With the help of the comment from @plalx, I found a solution in this thread:

Stubbing virtual attributes of Mongoose model

Upvotes: 1

Related Questions