Reputation: 524
In my POST request, I'm saving a new document into my mongo database. After the database is saved, can I do a res.redirect to that exact document ID?? I'm unsure of how to do this. I can't find any tutorials, documentation, or stackoverflow questions that seem to answer exactly what I'm looking for.
Can I do something like this? Where the :id is the Id of the document I just saved in mongoose/mongo?
newItem.save().then(res.redirect('/results/:id');
I expect the user to submit a post request. I'm saving the information into a mongo document through mongoose. Then after saving it I'd like to redirect to a new URL with the ID of the saved item on that page.
Upvotes: 2
Views: 483
Reputation: 144
Of course you can.
The save()
method can accept a callback so you can get the _id
field of the saved document.
One way of do it would be:
newItem.save((err, itemSaved) => {
if(err) {
next(err);
}
const itemId = itemSaved._id;
res.redirect('/results/' + itemId);
});
Hopefully, this will solve your problem.
P.S.
There's no need to use a colon on redirect's path. Beware with that, 'cause using it will give you a Cast Error
.
Upvotes: 3