Slimani
Slimani

Reputation: 465

Why does the spread operator nest data in another object?

I have been working with mongoose. And To find a user by their Email I returned a mongoose Promise like this:

async function findByEmail({ email }) {
    return await userModel.findOne({ email }).exec()
}

This is when things get a little bit weird, When I want to return the user using the Spread operator of Javascript

const user1 = await findByEmail({email: [email protected]});
const user2 = {...user1};
console.log('user1',user1);
console.log('user2',user2);

User1 is like this:

{
"_id": "ck09o6bvq0000zxsv6vr57oll",
"name": "bobo",
"email": "[email protected]",
"password": "$2b$10$1zQd/3Sw6zJi9N42zGLaT.Re5tnbt.ANzZ1XoGA0LLWFpjc05ef.a",
"facebookId": null,
"googleId": null,
"createdOn": 1567868083622,
"approved": true,
"__v": 0
}

While User2 is like this:

"$__": {
  "strictMode": true,
  "selected": {},
  "getters": {},
  "_id": "ck09o6bvq0000zxsv6vr57oll",
  "wasPopulated": false,
  "activePaths": {
    "paths": {
      "approved": "init",
      "createdOn": "init",
      "password": "init",
      "email": "init",
      "name": "init",
      "_id": "init",
      "facebookId": "init",
      "googleId": "init",
      "__v": "init"
    },
    "states": {
      "ignore": {},
      "default": {},
      "init": {
        "_id": true,
        "name": true,
        "email": true,
        "password": true,
        "facebookId": true,
        "googleId": true,
        "createdOn": true,
        "approved": true,
        "__v": true
      },
      "modify": {},
      "require": {}
    },
    "stateNames": [
      "require",
      "modify",
      "init",
      "default",
      "ignore"
    ]
  },
  "pathsToScopes": {},
  "cachedRequired": {},
  "$setCalled": {},
  "emitter": {
    "domain": null,
    "_events": {},
    "_eventsCount": 0,
    "_maxListeners": 0
  },
  "$options": {
    "skipId": true,
    "isNew": false,
    "willInit": true
  }
},
"isNew": false,
"_doc": {
  "_id": "ck09o6bvq0000zxsv6vr57oll",
  "name": "bobo",
  "email": "[email protected]",
  "password": "$2b$10$1zQd/3Sw6zJi9N42zGLaT.Re5tnbt.ANzZ1XoGA0LLWFpjc05ef.a",
  "facebookId": null,
  "googleId": null,
  "createdOn": 1567868083622,
  "approved": true,
  "__v": 0
},
"$locals": {},
"$init": true
}

which is Actually a Mongoose wrapper. Can Someone Please tell me why is this happening? And Why user1 is not the same as user2?

Upvotes: 0

Views: 536

Answers (1)

Slimani
Slimani

Reputation: 465

The spread operator in Javascript makes the object and instance of Object instead of saving its previous Class.

console.log(user1.constructor.name) //model
console.log(user2.constructor.name) //object

that's why there are more fields in the user2.To get only the _doc from user2 (thanks to this answer ) use toString like this

console.log(...user1.toObject())

Upvotes: 1

Related Questions