【发布时间】:2020-09-12 23:48:24
【问题描述】:
如果尚未创建集合,如何在 mongoose 事务期间自动创建集合?
我知道 mongoose 限制会限制用户在打开的事务会话期间创建(或删除)mongoose 集合。
此外,我还找到了 3 种可能的解决方案来解决这个问题:
1.autoCreate option
2.Model.init() method
3.Model.createCollection() method
使用哪一个?不会丢失索引等。
app.models.ts
import { model, Schema } from 'mongoose';
const UserSchema = new Schema<UserDocument>({
name: {
type: Schema.Types.String,
required: true,
}
}); // { autoCreate: true } <-- ???
export const UserModel = model<UserDocument>('User', UserSchema);
app.ts
import { startSession } from 'mongoose';
import { UserModel } from './app.models.ts';
async function createUser() {
// await UserModel.createCollection(); ??
// or
// await UserModel.init(); ??
const session = await startSession();
sesssion.startTransaction();
try {
const [user] = await UserModel.create([{ name: 'John' }], { session });
await session.commitTransaction();
return user;
} catch (error) {
await session.abortTransaction();
} finally {
session.endSession()
}
}
foo();
【问题讨论】: