【问题标题】:Why are mongoose query result objects so verbose in new version?为什么 mongoose 查询结果对象在新版本中如此冗长?
【发布时间】:2020-03-03 17:45:19
【问题描述】:

我在一台新计算机上安装了我的依赖项,它必须更新了 mongoose。 我从查询中得到的所有信息结果都返回到这些混乱中,其中包含很多有时可能有用但通常无用的信息。非常冗长。

例如,当它在查询承诺中运行 console.log(result) 时,它曾经返回如下内容:

user: {
    _id: '2c918aa5-3d5f-4397-8dd9-35c3675f53a2',
    email: 'ayeman@gmail.com',
    username: 'ayeman',
    password: '$2b$10$1sBah/12s12Ox0971221nk5g2s12s11FVRCW',
    watching: '',
    __v: 0
}

现在它返回这个:

model {
  '$__': InternalCache {
    strictMode: true,
    selected: {},
    shardval: undefined,

    .....

    *200 plus lines of verbose data*

    ....

      remove: [Function: pull],
      _path: 'chats',
      isMongooseArray: true,
      validators: [],
      _schema: [SchemaArray]
    ],
    _id: '2c918aa5-3d5f-4397-8dd9-35c3675f53a2',
    email: 'ayeman@gmail.com',
    username: 'ayeman',
    password: '$2b$10$1sBah/12s12Ox0971221nk5g2s12s11FVRCW',
    watching: '',
    __v: 0
  },
  '$init': true
}

我这辈子都找不到文档将其恢复为旧样式。

找到我所有的控制台日志并手动删除额外的数据似乎很愚蠢。 有没有办法改回来?我正在寻找类似 mongoose.model.options.changeResultsStyle() 之类的东西,但我找不到任何东西

【问题讨论】:

  • 你试过.lean()把你的结果对象变成一个json blob吗?
  • 几秒钟前才发现它。似乎旧猫鼬默认为 .lean();这种方式实际上更好,因为该信息在某些情况下可能是相关的。感谢您的回复!

标签: javascript reactjs mongodb express mongoose


【解决方案1】:

在新的 mongoose 版本中,它似乎默认为详细结果。在 mongoose 查询方法上使用 .lean() 将返回旧 mongoose 版本默认的精益样式。

我的示例场景

User.findOne({username: req.body.username }, {friends: 1}, function(err, result) {
    if (err) throw err;
    console.log(result.friends[1].pending)
    res.json(result.friends[1].pending);
}).lean();

{ _id: '2c918aa5-3d5f-4397-8dd9-35c3675f53a2', 朋友:[{已确认:[Array]},{待定:[Array]}], 状态:'离线', 聊天: [ { 确认: [Array] },{ 待定: [Array] } ], 电子邮件:'ayeman@gmail.com', 用户名:'ayeman', 密码:'$2b$10$gq0OrbxulaUBah/O.LhfjuiOx0970brivNStLXnk5gGn0QYRFVRCW', 观看: '', __v: 0 }

【讨论】:

    猜你喜欢
    • 2015-01-25
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    相关资源
    最近更新 更多