如果尚未创建集合,如何在 mongoose 事务期间自动创建集合?
我知道 mongoose 限制限制用户在打开的事务 session 期间创建(或删除)mongoose 集合。
另外,我找到了 3 种可能的解决方案来解决这个问题:
1. autoCreate
option
2. Model.init()
method
3. Model.createCollection()
method
使用哪一个?不丢失索引等
应用程序模型.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);
应用.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();
最佳答案
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.
无论如何,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在启动应用程序之前创建集合和索引的包。
https://stackoverflow.com/questions/62017666/
相关文章:
r - 在创建列表 tibble 列时在 "mutation"中使用 dplyr::sym() 会导
docker - 如何处理 make missing from alpine docker imag
python - psutil.AccessDenied : psutil. AccessDenie
google-cloud-functions - GCP Console : console. lo
ethereum - 返回错误 : The method web3_clientVersion do
reactjs - React Rich Text Editor 真的可以在移动设备上运行吗?
python - 在 tensorflow 2.0 中保存和加载模型