'How to add attribute to the result of mongoose query before res.status(200).send(result);

I am trying to build a CRUD API that query a mongodb. I want to add another attribute (temperature) to the query result before sending it back to the client. Particularly, I would like to do something where the arrow pointed in the code below.

app.get('/items/:name', function (req, res) {
    console.log("get items by name");
    Item.find({ name: req.params.name }, function (err, result) {
        if (err) {
            res.status(400).send(err.message);
        } else {
            res.status(200).send(result); // <<<<====== Here
        }
    });
});

How can I achieve this function? Thank you.



Solution 1:[1]

i think this below way to help you:

app.get('/items/:name', function (req, res) {
    console.log("get items by name");
    Item.find({ name: req.params.name }, function (err, result) {
        result = {
           temperature: yourTemperatureValue,
           ...result
        } // <<<<====== Here
        if (err) {
            res.status(400).send(err.message);
        } else {
            res.status(200).send(result); 
        }
    });
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1