How to retrieve the last added record from the database in the MERN technology stack? How to retrieve the last added record from the database in the MERN technology stack? mongoose mongoose

How to retrieve the last added record from the database in the MERN technology stack?


The last document added to the collection can be retrieved using findOne and sort _id -1

await <Model>.findOne().sort({_id:-1})

In your case, you can use the following

 const orders = await Order.findOne({ user: req.user._id }).sort({_id:-1})


Updating your query on the backend should fix it.

Try this:

const getLastOrder = asyncHandler(async (req, res) => {    const lastOrder = await Order.findOne({})    .sort({ _id: -1 })  res.json(lastOrder)})

All documents in mongoDb are created with the _id which contains the timestamp of insertion. Hence sorting using _id : -1 would get you the latest document available.Also, findOne will already get you a single document, hence there is no need to add limit to it.


You said that "this is not a fully satisfactory solution for me". So I think, you can change "react-action" part. I mean, on client side you catch the last '_id' of whole data from api. You don't have to do what you hate.I don't know structure of your code and your api, so understand following code if it has some wrong.

export const getMyLastOrder = () => async (dispatch, getState) => {try {  // I will omit the unnecessary parts.  // ...    const { data } = await axios.get(`/api/orders/myorders`, config);        let max = 0;        for(let i = 0; i < data.length; i++){        let id2Number = Number('0x' + data[i]._id);        if(id2Number > max){        max = id2Number;      }    }            data = max;    dispatch({      //...      payload: data,    })  } catch (error) {    // ...  }}