Luiz Henrique
Luiz Henrique

Reputation: 103

Receiving ONLY a value in field

I'm having trouble using .find() command, where I would receive only the value of the "TEMP" in the example below: "31"

[
    { 
        "_id": "57fb8cfee9eb8fc824000003",
        "data": "2016-10 10T12:43:42.168Z",
        "temp": "31",
        "__v": 0
    }
]

My view on Node.js is:

router.get('/ Temperature', function (req, res) {
    SHTemp.find({}).sort({_ id: -1}).limit(1)
    .exec(function (err, lasttemp) {
        if (err) {
            res.send('error found');
        } else {
            res.send(lasttemp);
        }
    })
})

The idea was lasttemp, send the value of the last temperature recorded in the collection. How can I do this?

Upvotes: 0

Views: 28

Answers (3)

Sachin
Sachin

Reputation: 2922

Try below.it will return key value for lasttemp

router.get('/Temperature', function (req, res) {
    SHTemp.find({},{temp:1}).sort({_ id: -1}).limit(1)
    .exec(function (err, lasttemp) {
        if (err) {
            res.send('error found');
        } else {
            res.send(lasttemp);
        }
    })
})

Upvotes: 0

Victor Parmar
Victor Parmar

Reputation: 5779

Try sorting on the data field if you would like to have the most recent temperature: SHTemp.find({}).sort({data: -1}).limit(1)

Also, you should ideally rename it from data to date and set the type to Date

Upvotes: 0

andresk
andresk

Reputation: 2845

find will always return an array with all the documents that match the query. If you want only the '31' value in this case, the simplest way is doing:

router.get('/ Temperature', function (req, res) {
SHTemp.find({}).sort({_ id: -1}).limit(1)
.exec(function (err, temps) {
    if (err or !temps) {
        res.send('error found');
    } else {
        res.send(temps[0].temp);
    }
  })
})

You could also check findOne in order to return just one document without needing to limit to one and getting the first element of the array.

Upvotes: 1

Related Questions