node.js - Typescript 中的 Mongoose.startSession 是什么类型?
问题描述
我有一个使用猫鼬的 Express/Typescript 项目,制作了一个像这样的加载器:
import mongoose from 'mongoose';
import { Db } from 'mongodb';
import config from '../config';
export default async (): Promise<Db> => {
const connection = await mongoose.connect(config.databaseURL, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
return connection.connection.db;
};
export async function withTransaction (func: any) {
const session = await mongoose.startSession();
session.startTransaction();
try {
await func(session);
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
throw error;
} finally {
session.endSession();
}
}
我想做一笔交易,我做了什么:
return await withTransaction(async (session: ClientSession) => {
try {
const newTransit = await Transit.create(userData, {session});
//...some other inserts
} catch (e) {
throw e;
}
}
Typescript 在会话类型上显示此错误:
TS2769: No overload matches this call.
The last overload gave the following error.
Argument of type '{ session: ClientSession; }' is not assignable to parameter of type '(err: NativeError, doc: ITransit & Document<any, {}>) => void'.
Object literal may only specify known properties, and 'session' does not exist in type '(err: NativeError, doc: ITransit & Document<any, {}>) => void'.
我应该为会话使用什么类型?
解决方案
我发现要在 create 方法中使用选项,我们必须将第一个参数作为数组传递。所以它会是这样的:
const newTransit = await Transit.create([userData], {session});
然后我们应该在需要 MongoDB 副本集的连接字符串中添加 retryWrites=false。以下是更多信息:
MongoError:此 MongoDB 部署不支持可重试写入。请将 retryWrites=false 添加到您的连接字符串
推荐阅读
- python - 获取二进制变量的值
- python - 将文本文件中的行附加到列表中时,它将整行设置为字符串。如何识别文本文件中的不同数据类型?
- rest - curl PUT 返回 HTTP/1/1 403 禁止 Authentication required 虽然通过了凭据
- php - 正确的 API 调用以启动 OpenID 连接
- python - 将字符串拆分为 list1
- query-optimization - 在 Virtuoso 中更改 SPARQL 查询的 SQL 转换
- go - 如何从通道接收直到它在 GO 中有值
- swift - 如何从 appdelegate 打开弹出窗口?
- javascript - 从 JavaScript 扩展 TypeScript 接口:TypeError: Class extends value undefined is not a function or null
- java - Java AWS SDK V2“getObject”跟踪进度