gpt4 book ai didi

javascript - MongoDB/mongoose - 后保存 Hook 未运行

转载 作者:可可西里 更新时间:2023-11-01 10:00:08 26 4
gpt4 key购买 nike

我有这个模型/架构:

const InviteSchema = new Schema({
inviter: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', required: true},
organisation: {type: mongoose.Schema.Types.ObjectId, ref: 'Organisation', required: true},
sentTo: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', required: true},
createdAt: {type: Date, default: new Date(), required: true}
});

InviteSchema.post('save', function(err, doc, next) {

// This callback doesn't run
});

const Invite = mongoose.model('Invite', InviteSchema);

module.exports = Invite;

辅助函数:

exports.sendInvites = (accountIds, invite, callback) => {

let resolvedRequests = 0;

accountIds.forEach((id, i, arr) => {

invite.sentTo = id;

const newInvite = new Invite(invite);

newInvite.save((err, res) => {

resolvedRequests++;

if (err) {

callback(err);

return;
}

if (resolvedRequests === arr.length) {
callback(err);
}
});
});
};

以及调用辅助函数的路由器端点:

router.put('/organisations/:id', auth.verifyToken, (req, res, next) => {

const organisation = Object.assign({}, req.body, {
updatedBy: req.decoded._doc._id,
updatedAt: new Date()
});

Organisation.findOneAndUpdate({_id: req.params.id}, organisation, {new: true}, (err, organisation) => {

if (err) {
return next(err);
}

invites.sendInvites(req.body.invites, {
inviter: req.decoded._doc._id,
organisation: organisation._id
}, (err) => {

if (err) {
return next(err);
}

res.json({
error: null,
data: organisation
});
});
});
});

这里的问题是 .post('save') Hook 没有运行,尽管遵循了说明,即在模型上使用 .save()例如,代替 .findOneAndUpdate。我已经挖掘了一段时间,但我看不出这里的问题是什么。

Invite 文档被保存到数据库中,因此 Hook 应该触发,但没有触发。有什么想法可能是错误的吗?

最佳答案

您可以使用不同数量的参数声明 post hook。使用 3 个参数处理错误,因此只有在出现错误时才会调用 post hook。但是,如果你的钩子(Hook)只有 1 或 2 个参数,它将在成功时执行。第一个参数将是保存在集合中的文档,第二个参数(如果传递)是下一个元素。更多信息,查看官方文档:http://mongoosejs.com/docs/middleware.html希望对您有所帮助。

关于javascript - MongoDB/mongoose - 后保存 Hook 未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47437948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com