Mongoose 在 insertMany 方法上触发保存后钩子

问题描述 投票:0回答:1

我正在将客户数据植入 mongodb 数据库。 我想根据出生年份将客户属于哪一代群体(例如 Z 世代、X 世代、千禧一代等)保存在单独的集合中。我使用 insertMany 方法来保存客户的信息,而不是 create 或 save 方法。

而且我也不打算使用创建或保存方法。

如何在 insertMany 方法上触发保存后中间件?我需要传递任何选项来触发 insertMany 方法上的保存后中间件吗?

CustomerSchema.post('save', async function (doc) {
    try {
        const year = doc.birthDate.getFullYear();
        console.log({ year });
    } catch (error) {
        throw error;
    }
});
mongodb mongoose
1个回答
1
投票

您需要专门为

insertMany
声明一个post hook。
如果您想在
save
钩子中运行相同的代码,您可以将通用逻辑提取到函数中:

const postSaveHook = async (doc) => {
    try {
        const year = doc.birthDate.getFullYear();
        console.log({ year });
    } catch (error) {
        throw error;
    }
};

CustomerSchema.post('save', postSaveHook);

CustomerSchema.post('insertMany', async (docs, next) => {
    for (const doc of docs) {
        await postSaveHook(doc);
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.