首页 > 解决方案 > MongooseError - 操作缓冲在 10000 毫秒后超时

问题描述

我有以下模型代码。

import { DatabaseServer } from './database-server';
import { ProjectGroup } from './project-group';
import { ProjectUser } from './project-user';
import { prop, getModelForClass, ReturnModelType, modelOptions } from '@typegoose/typegoose';
import { defaultTransform, ModelBase } from '../general/model-base';
import { ObjectID } from 'mongodb';
import { Connection } from 'mongoose';
import { BeAnObject } from '@typegoose/typegoose/lib/types';

export class Datasource extends ModelBase {

  @prop()
  databaseServer?: DatabaseServer;
  @prop()
  databaseServerId?: ObjectID;
  @prop()
  datasource?: Datasource[];

  @prop()
  name?: string;
  @prop()
  projectGroups?: ProjectGroup[];
  @prop()
  projectUsers?: ProjectUser[];

}

const DatasourceModel = (
  connection: Connection,
): ReturnModelType<typeof Datasource, BeAnObject> => {
  return getModelForClass(Datasource, {
    ...defaultTransform,
    ...{
      existingConnection: connection,
    },
  });

};
export { DatasourceModel };

我正在使用上述模型如下。

await DatasourceModel(await this.masterContext).find({})

其中 mastercontext 定义如下。

import {
  Connection,
  createConnection
} from 'mongoose';

export class MasterContext {
  get context(): Promise<Connection> {
    if (!this.m_context) {
      this.m_context = createConnection('mongodb://localhost/Master', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      });
    }

    return this.m_context;
  }
  private m_context: Promise<Connection>;
}

我收到如下错误。

Operation datasources.find() buffering timed out after 10000m

如果我将类名从更改export class Datasource为任何其他名称(例如export class Datumsource),则不会抛出错误。

那么DatasourceMongoDb 或 Mongoose 或 Typegoose 中的保留关键字是什么?

标签: node.jstypescriptmongodbmongoosetypegoose

解决方案


据我所知,这个错误意味着连接没有连接,所以命令(find)有超时

我还建议缓存DatasourceModel或者只运行一次函数(不需要连接连接来创建模型,只需要连接来执行命令(如find))
所以如果你有一个全局连接,你应该简单地删除函数并运行getModelForClass,但如果你有一个“本地”连接(比如来自类属性),那么你应该把它缓存在那里,例如:

// i think this way of defining stuff is common in nestjs?
class Dummy {
  public connection: mongoose.Connection;
  public model: mongoose.Model;

  constructor(connection: mongoose.Connection) {
    this.connection = connection;
    this.model = getModelForClass({ ...otherGlobalStuff, existingConnection: connection });
    // or when wanting to use your function
    this.model = DatasourceModel(connection);
  }
}

// and if for one file only
let model = DatasourceModel(connection);

其他一些注意事项:

  • 如果你想在 typegoose 中使用数组,你需要使用type选项手动定义类型,看这里为什么
  • 只有mongoose.Types.ObjectId类型应该用于ObjectId

推荐阅读