【问题标题】:refers to a value, but is being used as a type here指的是一个值,但在这里被用作一个类型
【发布时间】:2021-07-12 16:21:11
【问题描述】:

我是 typescript 和 node.js 的新手,而且我正在尝试使用 typescript 和 node.js 我用 mongoose 创建了一个模型并将其导入到我的 users.service.ts 文件中,但是当我使用它时出现此错误 CreateUserDto' refers to a value but is being used as a type here. Did you mean 'typeof CreateUserDto'? 我创建了一个名为 users.ts 的文件,这是我的模型,还创建了一个名为 users.service.ts 的文件,您可以在下面找到这些文件的代码,请帮助我,我可以修复错误,非常感谢。

Error Image 型号:users.ts

import * as mongoose from 'mongoose';
// import IUser from "../interface/users"
import { Schema, Document } from 'mongoose';

export interface IUser extends Document {
  firstName: String,
  lastName: String,
  email: String,
  password: String
}

const UserSchema: Schema = new Schema({
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  }
}, {
  timestamps: true
});
export default mongoose.model<IUser>('User', UserSchema);

users.service.ts

import UsersDao from '../daos/users.dao';
import { CRUD } from '../../common/interfaces/crud.interface';
import CreateUserDto from "../model/users";
import { PutUserDto } from '../dto/put.user.dto';
import { PatchUserDto } from '../dto/patch.user.dto';

class UsersService implements CRUD {

    async create(resource: CreateUserDto) {
        return UsersDao.addUser(resource);
    }

    async deleteById(id: string) {
        return UsersDao.removeUserById(id);
    }

    async list(limit: number, page: number) {
        return UsersDao.getUsers();
    }

    async patchById(id: string, resource: PatchUserDto) {
        return UsersDao.patchUserById(id, resource);
    }

    async readById(id: string) {
        return UsersDao.getUserById(id);
    }

    async putById(id: string, resource: PutUserDto) {
        return UsersDao.putUserById(id, resource);
    }

    async getUserByEmail(email: string) {
        return UsersDao.getUserByEmail(email);
    }
}

export default new UsersService();

【问题讨论】:

  • 将您的项目升级到打字稿。

标签: javascript node.js mongodb typescript mongoose


【解决方案1】:

CreateUserDtomongoose 模型,这不是 typescript 的有效类型描述符。您可以阅读所有有效的 ts 类型 here

您想要做的是使用您创建的IUser 接口,而不是像这样:

async create(resource: IUser) {
   return UsersDao.addUser(resource);
}

【讨论】:

  • 我想在 MongoDB 中保存数据或从我的数据库中查找用户,但我无法通过界面执行这些操作
  • 接口只描述了ts编译器的类型,不包含任何实际数据。当您将代码编译为 javascript 接口“消失”时,您可以看到这一点。
猜你喜欢
  • 2020-03-23
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 2021-07-07
  • 2017-08-16
  • 1970-01-01
相关资源
最近更新 更多