The correct way to create collection during mongoose transaction

Viewed 667

How to autocreate collection during mongoose transaction if the collection was not created yet?

I'm aware of mongoose limitation that restricts user to create (or delete) mongoose collections during open transaction session.

Also, I was able to find 3 possible solutions on how to fix that:
1. autoCreate option
2. Model.init() method
3. Model.createCollection() method

Which one to use? Without losing indexes etc.

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();
1 Answers

If a collection does not exist, MongoDB creates the collection when you first store data for that collection. You can also explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.

Anyway, mongoose takes care of indexes, collection, etc... you just need to define the collection name: https://mongoosejs.com/docs/guide.html#collection

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

There is the answer about transactions and collection creating -https://github.com/Automattic/mongoose/issues/6699

Actually, I use https://www.npmjs.com/package/db-migrate package to create collections and indexes before starting an app.

Related