Ticket: User Mangement - addUser - insertOne requires ... (Spreadable)?

Hello,

So, I know this is down to a lack of understanding, but I am looking for an explanation, of why, this didn’t work: -

await users.insertOne(userInfo)

Since userInfo is already an object, and I tried it out in the playground before inserting it into the addUser function.

And why we needed to make userInfo spreadable?
Spread syntax (…) - JavaScript | MDN (mozilla.org)

await users.insertOne({…userInfo})

I finally broke the insertOne into it’s component parts to get it to work, but neither the less I am intrigued into the why.

Thank you

Hello,

So, after a lot of angst I think I get it.

  1. This command → console.log(userInfo); produced this output: -

    {
    name: ‘Magical Mr. Mistoffelees’,
    email: ‘magicz@cats.com’,
    password: ‘somehashedpw’
    }

    When tied with this command →

    await users.insertOne(userInfo);

    The user-management test script would fail.

  2. This command → console.log({ … userInfo} ); produced this output: -

    {
    name: ‘Magical Mr. Mistoffelees’,
    email: ‘magicz@cats.com’,
    password: ‘somehashedpw’
    }

    The output of the 2 console logs look the same, however the command : -

    await users.insertOne({…userInfo});

    Works.

So the { … userInfo } within the insertOne converts the Javascript object into a set of name value pairs, which conform to the requirements of a Mongodb document?

In the ticket notes for User Management, that would have been one I could have done with a full explanation :slight_smile:

Javascript objects and Mongodb documents = If it walks like a duck, talks like a duck, but in this case it isn’t a duck.

2 Likes

No, it’s because the {…userInfo} construction makes a copy of the object and just giving userInfo does not. This is significant because the insertOne() call alters the supplied object, so the test will fail because it is not expecting testUser to change (it’ll get an _id inserted).

So you can either change the addUser() so that it doesn’t affect the data passed to it (by creating a copy that it send to insertOne()), or change the test so that it does the comparison expecting the _id to now be present in both user and testUser (or removed from both!). I imagine the former is what the writers intended!

2 Likes