简体   繁体   中英

Creating Express param middleware that updates the request object

Im trying to update the req.conversation before its handled by another function called read. I know the middleware is being called before read but when I log the req.conversation object in read it doesnt reflect the updates made in the middleware.

/**
* Conversation middleware
*/
exports.conversationByID = function(req, res, next, id) {

    if (!mongoose.Types.ObjectId.isValid(id)) {
        return res.status(400).send({
            message: 'Conversation is invalid'
        });
    }

    Conversation.findById(id).populate('user', 'displayName').populate('readers', 'displayName').exec(function(err, conversation) {
        if (err) return next(err);
        if (!conversation) {
            return res.status(404).send({
                message: 'Conversation not available'
            });
        }
        req.conversation = conversation;
        next();
    });
};

Where is the id parameter in your middleware callback coming from? If it's a url param (eg /conversations/:id ) it should be req.params.id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM