Nodejs + Mongoose + Typescript “这个表达式不可调用。”在 .populate()

问题描述 投票:0回答:1

我在 Node JS 中有一个带有 mongoDB 和 Typescript(在撰写本文时均为最新版本)的项目,但我无法启动。谁能帮帮我?

我遇到的问题如下(即由于 .populate() 上的问题我无法编译):

/Users/{...}/Projects/{...}/node_modules/ts-node/src/index.ts:843
    return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
TSError: ⨯ Unable to compile TypeScript:
src/apis/v1/controllers/users/update.controller.ts:136:35 - error TS2349: This expression is not callable.
  Each member of the union type '{ <Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[]): Promise<MergeType<Document<unknown, any, UserDocument> & { ...; } & UserDocument & { ...; }, Paths>>; <Paths = {}>(path: string | ... 1 more ... | (string | PopulateOptions)[], callback: Callback<...>): void; <Paths = {}>(path: string, se...' has signatures, but none of those signatures are compatible with each other.

136       savedData = await savedData.populate('createdBy', config.userPopulate);

我有一个包含以下包的项目:

{
  "dependencies": {
    "express": "^4.18.1",
    "mongoose": "^6.4.2",
    "typescript": "^4.7.4",
  },
}

以下是创建用户模块涉及的文件:

// Interface
interface User {
  _id: string | Types.ObjectId;

  ...
  givenName: string;
  familyName: string;
  ...

  createdBy?: string | Types.ObjectId;
  createdAt: Date;
  updatedBy?: string | Types.ObjectId;
  updatedAt: Date;
  __v?: number;
}

// Model
const UserModel = mongoose.model<UserDocument, UserModelDef>('User', userSchema);

// Schema
export interface UserDocument extends User, Document {}
export interface UserModelDef extends Model<UserDocument> {}
const { Schema } = mongoose;
export const userSchema = new Schema<UserDocument, UserModelDef>(
  {
    ...

    givenName: {
      type: Schema.Types.String,
      required: true,
      trim: true,
      minlength: 2,
      maxlength: 50,
    },
    familyName: {
      type: Schema.Types.String,
      required: true,
      trim: true,
    },

    ...

    createdBy: {
      type: Schema.Types.ObjectId,
      required: false,
      ref: 'User',
    },
    updatedBy: {
      type: Schema.Types.ObjectId,
      required: false,
      ref: 'User',
    },
  },
  {
    timestamps: true,
  },
);

发生错误的代码

const item = await UserModel.findById(userId);
item.set('givenName', 'John');
item.set('updatedBy', req.userLoggedIn?._id);
let savedData = await item.save();
savedData = await savedData.populate('updatedBy', config.userPopulate);
node.js typescript mongoose mongoose-populate
1个回答
0
投票

任何解决方案?填充文档项目时出现同样的错误

© www.soinside.com 2019 - 2024. All rights reserved.