0

This is my weather model:

// Declare schema
var weatherSchema = Schema({
    data: {
        type: Object
    },
    date: {
        type: String,
        required: true
    },
    created_at: {
        type: Date,
        default: Date.now,
        index: 1
    }
});

in date field, I store dates such as 2017-7-1, 2017-7-2, 2017-7-3, etc

Now I have many docs in this weather table, from 2017-6-20 to 2017-7-3 for instance.

So I want to retrieve the docs from 2017-7-1 to 2017-7-2 only:

Weather
.find({})
.where('date').gt('2017-7-1').lt('2017-7-2')
.exec(function (err, docs) {
    console.log(docs);
    if (err) {
        res.set('Content-Type', 'application/json');
        return res.sendStatus(-1);
    }

    if (!docs) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Not weather data found.');
    }
    // return docs as json.
    return res.status(200).json(docs);
});

But what I get is []. What have I done wrong?

Any ideas?

EDIT:

The official format above does not work, but it works with this format:

var options =  {
    "date": {
        "$gte": start,
        "$lt": end
    }
}

Weather
.find(options, function (err, docs) {
    console.log(docs);
    if (err) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Error occurs: ' + err);
    }

    if (!docs) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Not weather data found.');
    }
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE');

    // return docs as json.
    return res.status(200).json(docs);
}).select("-created_at -_id -__v");

Why?

Run
  • 54,938
  • 169
  • 450
  • 748

1 Answers1

1

To compare a dates the date field should be a Date type. and then you can search like:

.where('date').gt(new Date('2017-7-1')).lt(new Date('2017-7-2'))

Or If you want use date as a string, you can search like this:

.where('date').in(['2017-7-1', '2017-7-2'])

This query will find entries with exact date string ('2017-7-1' or '2017-7-2')

O. Borcuhin
  • 234
  • 2
  • 5