-1

I have to add a property for an object returned from my db before pushing it to an array. Changing properties work, but adding new ones doesn't. Can anyone can explain the logic behind this behavior?

 ids.forEach(async (id, index) => {  
                //get object without highlight property  
                let real_a = await database.getA(id)
                real_a.highlight = "shoud add highlight property to real_a object"
                realItems.push(real_a)
                // the correct string is printed
                console.log(real_a.highlight)
                //object still doesn't have that property
                console.log(real_a)
                }
Tudor Sandu
  • 21
  • 1
  • 4
  • Please post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Ele Jul 06 '18 at 07:36
  • 1
    Side note: You're breaking one of the main rules of promises in that code. You must either handle possible errors, or propagate the promise to something that will (directly or indirectly). But in your code above, nothing handles errors, and `forEach` throws away the promises your `async` function creates so nothing else can, either. – T.J. Crowder Jul 06 '18 at 07:37
  • Hi! What you're describing isn't possible, though if something deletes the property later you might *seem* to see that in the console because of [this behavior](http://stackoverflow.com/questions/38660832/) or because the property is a setter and you're not looking deeply enough in the object's prototype chain (seems unlikely, but...). Please update your question with a [mcve] demonstrating the problem, ideally a **runnable** one using Stack Snippets (the `[<>]` toolbar button; [here's how to do one](https://meta.stackoverflow.com/questions/358992/)). – T.J. Crowder Jul 06 '18 at 07:43
  • Stack Overflow is a *very active place*. When you post a question (or answer), please *stick around* for a few minutes so you can respond to comments asking for clarification, etc. :-) – T.J. Crowder Jul 06 '18 at 08:32
  • Sure, sorry for that. While I was writing the snippet I figured that It was probably something else since it should have worked as intended under usual circumstances. Got the answer by searching for related database issues. – Tudor Sandu Jul 06 '18 at 08:48

1 Answers1

0

It was the intended behavior.Sorry for bothering.

I was using a mongodb query for the database.getA(id) function and it turns out you have to specify a parameter in the mongodb query to get an actual changeable JSON object.

Here is the complete answer:

Why can't you modify the data returned by a Mongoose Query (ex: findById)

Tudor Sandu
  • 21
  • 1
  • 4