node.js - 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
),则不会抛出错误。
那么Datasource
MongoDb 或 Mongoose 或 Typegoose 中的保留关键字是什么?
解决方案
据我所知,这个错误意味着连接没有连接,所以命令(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
推荐阅读
- spring - Spring Cloud 网关 oauth2 登录
- python - Tensorflow概率:保存和加载模型
- c++ - 如何从智能指针.get()中删除分配运算符重载?
- javascript - 如何将 PNG 块转换为 PNG 图像?
- shell - 如何使用 sed/aws 从 json 文件中获取值?
- airflow - Airflow - Great Expectations - 将评估参数发送到 GreatExpectationsOperator
- java - Webview 导致应用程序在启动时立即崩溃
- gradle - 如何在 gradle 7.1.1 中将配置更改为 checkstyle 插件的 configDirectory?
- xml - 如何使用 xslt 过滤每个不同元素和属性的第一次出现
- tensorflow - 为什么我的 Convnet 本质上只是学习所有 y_values 的平均值?