Spread语法返回意外对象

Sar*_*hah 4 javascript node.js spread-syntax

我正在使用节点,我已经使用过.

巴贝尔节点

    "start": "nodemon --exec babel-node --presets es2015 index.js"
Run Code Online (Sandbox Code Playgroud)

我的传播语法没有按预期工作.这是我的代码.

   export const login = async (parentValue, { email, password }) => {
  try {
    const user = await User.findOne({
      email
    });
    console.log(user);

    if (!user.authenticateUser(password)) {
      throw new Error('Wrong password');
    }
    const dummyObject = {
      ...user
    };
    console.log({ dummyObject });
    return { ...user };
  } catch (e) {
    console.log(e);
    throw new Error(e.message);
  }
};
Run Code Online (Sandbox Code Playgroud)

我使用的线console.log(user),它工作正常.它回来了 { id: xxx, name: xxxx }

我得到了意想不到的数据console.log(dummyObject); 这就是我得到的.

{ jojo: 
{ '$__': 
      InternalCache {
        strictMode: true,
        selected: {},
        shardval: undefined,
        saveError: undefined,
        validationError: undefined,
        adhocPaths: undefined,
        removing: undefined,
        inserting: undefined,
        saving: undefined,
        version: undefined,
        getters: {},
        _id: 5c798295f53323b34cabf1ca,
        populate: undefined,
        populated: undefined,
        wasPopulated: false,
        scope: undefined,
        activePaths: [Object],
        pathsToScopes: {},
        cachedRequired: {},
        session: undefined,
        ownerDocument: undefined,
        fullPath: undefined,
        emitter: [Object],
        '$options': [Object] },
     isNew: false,
     errors: undefined,
     _doc: 
      { _id: 5c798295f53323b34cabf1ca,
        fullName: 'sarmad',
        password: '$2a$10$c.XDX75ORXYA4V/hUXWh.usVf2TibmKfY.Zpu3cpTssFaYvsGyhte',
        email: 'sarmad@gmail.com',
        createdAt: 2019-03-01T19:05:57.454Z,
        updatedAt: 2019-03-01T19:05:57.454Z,
        __v: 0 },
     '$init': true } }
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么?从技术上讲,它应该返回用户对象注意:我不想使用Object.assign

Tom*_*Con 9

看起来你正在使用mongoose,看起来你通过使用spread运算符来获取mongoose对象属性.你需要转换为JSON来摆脱这些.

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

你也可以: const dummyObject = { ...user.toObject() };

^这可能是首选方式

另一种解决方案是在进行查询时仅请求普通对象.例如:

Schema.findOne(query).lean()

这将返回一个普通对象而不是一个猫鼬对象.