【问题标题】:When working with sessions, timestamps are not added使用会话时,不会添加时间戳
【发布时间】:2023-01-29 21:20:23
【问题描述】:

我正在使用今天最新的猫鼬版本 (6.2.7),我遇到了一个非常奇怪的错误。

这是我的架构:

const testSchema = new Schema<ITestSchema>({
  age: Number
}, { timestamps: true });

const testModel = model<ITestSchema>("test", testSchema);

当我用它创建新系列时,一切都很完美!并且我将时间戳(updatedAt 和 createdAt)添加到集合中。

当我处理会话时,不会添加时间戳,我只看到“age”、“_d”和“__v”。

这是使用会话创建的示例代码:

const test = async () => {
    const session: ClientSession = await mongoose.startSession();

    try {
        session.startTransaction();

        const newTest = new testModel({
            age: 30,
        }, { session });

        await newTest.save({ session });

        await session.commitTransaction();
    } catch (error) {
        await session.abortTransaction();
        throw error;
    } finally {
        await session.endSession();
    }
};

我尝试多次阅读文档并在线搜索类似问题但找不到任何问题。

谢谢 3>

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    我知道这个问题很老但是我刚刚遇到这个并找到了解决方案,你的错误是你在创建模型和保存时在两个不同的地方使用会话,问题是如果你只在 testModel 上使用会话它也不会工作,所以会话只能在调用保存功能时使用

    示例代码:

    const modelObject = {
        '_id' : new Types.ObjectId(),
        ...dto
    }
    
    const newItem = new this.model(modelObject)
    
    return newItem.save({
        session
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多