【问题标题】:Read object value in Nestjs problems在 Nestjs 问题中读取对象值
【发布时间】:2021-06-09 12:10:00
【问题描述】:

在 Nestjs 中读取对象时遇到问题

有代码

    @Post()
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: (req, file, cb) => {
          const userId = req.body.username;
          const usern = req.user;
          console.log(usern);

          const dir = `./public/avatar/${userId}`;
          fs.exists(dir, (exist) => {
            if (!exist) {
              return fs.mkdir(dir, (error) => cb(error, dir));
            }
            return cb(null, dir);
          });

console.log(usern) 返回

{
  _id: '6026654c957fe6330a6d54c2',
  status: 'active',
  iat: 1615467122,
  exp: 1615553522
}

但如果我尝试获取 req.user._id 则会出现错误 错误 TS2339:“用户”类型上不存在属性“_id”。

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    看起来像 TypeScript 错误,您的 User 类似乎没有 _id 属性。你应该在类中添加属性。

    【讨论】:

    • req.user return { _id: '6026654c957fe6330a6d54c2', status: 'active', iat: 1615467122, exp: 1615553522 },但我无法访问这些字段中的任何一个。例如 req.user.status 也会出错。
    • 问题不在于你的代码表现如何,而在于你的代码编译。 req.user 应该属于 User 类,因此当您询问 req.user._id 时,它会引发错误,因为您的类中不存在该属性。所以改变你的类以允许编译。
    猜你喜欢
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2021-08-15
    相关资源
    最近更新 更多