【问题标题】:What's the proper way to select certain fields in a query when you use Mongoose?使用 Mongoose 时,在查询中选择某些字段的正确方法是什么?
【发布时间】:2021-06-06 21:08:51
【问题描述】:

我阅读了documentation,其中描述了如何通过提取 id 找到的对象的某些字段来解决问题。我尝试编写类似的代码,但分配给 user 变量的输出包括单个元素的所有字段。

export const getUser = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const { id } = req.params;
    const userFetchesOwnData = req.app.locals.userId === id;
    let user: any;
    if (req.app.locals.isAuth && userFetchesOwnData) {
      user = await User.findById(
        id,
        "email username age sex location summary"
      ).exec();
    } else {
      user = await User.findById(
        id,
        " username age sex location summary"
      ).exec();
    }
    console.log(user);
    res.status(200).json({
      message: "User fetched",
      user,
    });
  } catch (err) {
    if (!err.statusCode) {
      err.statusCode = 500;
    }
    next(err);
  }
}; 

【问题讨论】:

  • 查询看起来很正确。用户变量应该具有所有选定的字段 + _id 字段。如果需要排除 _id 字段则需要添加-_id

标签: javascript node.js mongodb typescript mongoose


【解决方案1】:

您可以通过逗号分隔值来专门查询 Mongoose 对象中的字段。

User.findById(id).select("_id, email, username, age, sex, location, summary").then(...)

【讨论】:

  • 查询仍然返回完整数据。
  • 你用的是什么版本的猫鼬?
  • @BriahPhelps,现在是 5.11.19。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-16
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多