我有以下模型代码。
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
),则不会抛出错误。
MongoDb、Mongoose 或 Typegoose 中的 Datasource
是保留关键字吗?
答案 0 :(得分:1)
据我所知,此错误表示连接未连接,因此命令 (find
) 超时
我还建议缓存 DatasourceModel
或只运行一次函数(不需要连接来创建模型,只需要连接来执行命令(如 {{1 }}))
所以如果你有一个全局连接,你应该简单地删除函数并运行 find
,但是如果你有一个“本地”连接(比如来自类属性),那么你应该将它缓存在那里,例如:< /p>
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);
选项手动定义类型,look here on whytype
类型应该用于 mongoose.Types.ObjectId