Spread syntax returns unexpected object

青春壹個敷衍的年華 提交于 2019-12-01 18:52:51

Looks like you're using mongoose, and it looks like you're getting the mongoose object properties by using the spread operator. You need to convert to JSON to get rid of these.

Try: const dummyObject = { ...user.toJSON() };

You can also: const dummyObject = { ...user.toObject() };

^ This might be the preferred way

Another solution is to only request a plain object when making your query. For instance:

Schema.findOne(query).lean()

This will return a plain object instead of a mongoose object.

You get different logs because mongoose uses custom inspection function

Try this in node:

const obj = {
  [Symbol.for('nodejs.util.inspect.custom')]() {
    return "totally not an object";
  }
}

console.log(obj); // "totally not an object"

Since mongoose inspect is defined on object's prototype it isn't copied when you use ... since spread only copies object's own properties.

class Obj {
  [Symbol.for('nodejs.util.inspect.custom')]() {
    return "totally not an object";
  }
}

const obj = new Obj();
const obj2 = { ...obj };


console.log(obj); // "totally not an object"
console.log(obj2); // {}

You can fix it by setting a prototype to the copied object:

Reflect.setPrototypeOf(obj2, Reflect.getPrototypeOf(obj))

but since you are dealing with custom objects an object spread shouldn't be really used. Spread is safe only for POJO. Otherwise you may get into troubles easily (with hidden props, getters, setters and prototype hell)

https://repl.it/repls/ToughModestInstructionset

https://github.com/Automattic/mongoose/blob/master/lib/document.js#L2853:L2869

https://nodejs.org/api/all.html#util_util_inspect_custom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!