0

I'm beginner at programing and I don't know how can I do something with the mongoose save result. In my post endpoint I would like to not save and directly return but instead of it I would like to do something with the result of save method like take the _id value of the new object created and pass to a function.

Here's what my post endpoint is doing and I would like to after saving not return but instead call a function passing the checkout object created:

router.post('/', async function(req, res) {
    const { checkinId, eventId, email } = req.body;
    let CheckoutTest = {
        checkinId: checkinId,
        eventId: eventId, 
        email: email,
    } 
    const newCheckout = new Checkout(CheckoutTest);
    await newCheckout.save((err, checkout) => {
        if(err) {
           return res.status(400)
           .send(err);
        }else {
           return res.status(200)
           .json({message: "Checkout successfully added!", checkout});
        }
    })
});

1 Answer 1

2

An elegant way to do this would be to add a try...catch block

router.post('/', async function(req, res) {
        const { checkinId, eventId, email } = req.body;
        let CheckoutTest = {
        checkinId: checkinId,
        eventId: eventId, 
        email: email,
    } 
    const newCheckout = new Checkout(CheckoutTest);

    try {
        const newCheckoutObject = await newCheckout.save()
        // Call the function that you wanted to after the save. 
        // You can pass in the "_id" of the object as shown here
        const newData = await functionToBeCalled(newCheckoutObject._id)
        return res.status(200).json({message: "Checkout successfully added!", newData});
    } catch (err) {
        return res.status(400).send(err);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I don't want to return this: return res.status(200).json({message: "Checkout successfully added!", checkout}); I would like to return the return of the function I want to call

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.