Use GET to return records based on nested fields

Viewed 84

I am trying to retrieve records based on a value in a mongo dataset that is in a nested object.

data is an object and documentId is a field within it and I want to retrieve just the objects within data that have the documentId of "5da713edf0a1645ae95b11oo"

I tried this code

const res = await axios.get('/api/card',{
  params:{
    data:documentId: "5da713edf0a1645ae95b11oo"
  }
});

but it just returns all the records

4 Answers

Try one of these:

const res = await axios.get('/api/card',{
  params:{
    documentId: "5da713edf0a1645ae95b11oo"
  }
});

This would be a GET request to /api/card?documentId=5da713edf0a1645ae95b11oo

or

const res = await axios.get('/api/card',{
  params:{
    data: {
      documentId: "5da713edf0a1645ae95b11oo"
    }
  }
});

This would be a GET request to something like /api/card?data=%7B%22documentId%22%3A%225da713edf0a1645ae95b11oo%22%7D

...where %7B%22documentId%22%3A%225da713edf0a1645ae95b11oo%22%7D is URL encoded version of {"documentId":"5da713edf0a1645ae95b11oo"}

You can try this:

data_get() {
    axios.get('/api/card')
    .then((res) => {
        this.setState({
            documentId: res.data.id, //5da713edf0a1645ae95b11oo 
        });
    });
}

according to the documentations it says that we can not do what you have done.

axios.get('/api/card')
.then((res) => {
    const data = res.data.id;
    //handle your response here.
    //can write your logic to retrieve your specific data 
});

for further in formations refer this doc

I'm going to assume the data you're receiving on the response is an array of objects. You can filter through it. You're going to have to loop through the data though.

const res = await axios.get('/api/card')

const filteredData = res.data.filter((item) => item.documentId === '5da713edf0a1645ae95b11oo')
Related