【问题标题】:The correct way to create collection during mongoose transaction猫鼬事务期间创建集合的正确方法
【发布时间】: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();

【问题讨论】:

    标签: mongodb express mongoose


    【解决方案1】:

    如果集合不存在,MongoDB 会在您首次存储该集合的数据时创建该集合。您还可以使用各种选项显式创建集合,例如设置最大大小或文档验证规则。

    无论如何,mongoose 负责索引、集合等... 你只需要定义集合名称:https://mongoosejs.com/docs/guide.html#collection

    const UserSchema = new Schema<UserDocument>({
      name: {
        type: Schema.Types.String,
        required: true,
      }
    }, {collection: 'users'});
    

    关于事务和集合创建的答案-https://github.com/Automattic/mongoose/issues/6699

    实际上,我在启动应用程序之前使用https://www.npmjs.com/package/db-migrate 包来创建集合和索引。

    【讨论】:

    • 文档说:Set this option if you need a different name for your collection.。我不需要一个不同的名字。如果还没有创建,我需要在事务之前创建一个集合。
    • 我明白了,反正我上面提到过,集合是由MongoDB创建的。你不需要创建它
    • 您确定这种方法适用于 mongoose 交易吗?
    • 不,它不起作用。错误信息是Cannot create namespace test.filials in multi-document transaction.
    • 好的,我编辑了答案。您可以在启动应用程序之前检查 db-migrate 包并创建集合和索引。与 SQL 数据库相同的方法。
    猜你喜欢
    • 2018-03-19
    • 2020-03-23
    • 2020-08-01
    • 2021-05-11
    • 1970-01-01
    • 2023-03-09
    • 2012-03-07
    • 1970-01-01
    • 2014-09-25
    相关资源
    最近更新 更多