Home > front end >  Mongoose give aliases to fields before sending the data to client side
Mongoose give aliases to fields before sending the data to client side

Time:09-23

i have this function that returns employees as an array of objects and send it to client side

const getEmployees = async (req, res) => {
  try {
    const employees = await Employee.find({}, { __v: 0 });
    res.status(200).json(employees);
  } catch (err) {
    console.log(err);
    res.status(400).json(err);
  }
};

it looks like something like this :

[
{accountNumber: 1 , employeeName: john}
{accountNumber: 2 , employeeName: oscar}
{accountNumber: 3 , employeeName: franc}

]

TableContainer.js

function TableContainer({ table }) {

  const [data, setData] = useState([{}]);

  useEffect(() => {
    const getData = async () => {

        const response = await fetch("http://localhost:8000/get-employees");
        const data = await response.json();
        setData(data);
      
    };
    getData();
  }, []);

   return (
        <table className="table">

          <thead>
            <tr>
              {filteredData.length > 0 &&
                Object.keys(filteredData[0]).map((key) => (
                  <th key={key}> {key} </th>
                ))}
            </tr>
          </thead>

          <tbody>
            {filteredData.length > 0 &&
              filteredData.map((item, i) => (
                <tr key={i}>
                  {Object.values(item).map((val, i) => (
                    <td key={i}>{val}</td>
                  ))}
          </tbody>
        </table>
}

now the table headers will be accountNumber and employeeName, but this is not appropriate for user to read, i want them to rather be Account Number and Employee Name, is there a way to change fields names on the server side before sending the data rather than missing up with the array in the react component or change the fields names in the collection ?

CodePudding user response:

You should be able to just use the following projection:

const employees = await Employee.find({}, { 'Account number': '$accountNumber', 'Employee Name': '$employeeName'});
  • Related