简体   繁体   中英

Query with MongoDB and Node.js not returning any results

I'm new to Javascript, Node.ja and MongoDB and I'm having trouble getting results back into my Node.js server when specifying query parameters (works fine returning all records with no query).

My collection has a timestamp field in the format "yyyy-mm-dd hh:mm:ss" and I want to return all results where the hour is either '00', '06', '12' or '18' to drive chart (using chart.js)

On the mongo cmdline I can do the following:

db.MyCollection.find({ $or: [ {"timestamp": /.* 06:. /}, {"timestamp": /. 12:. /}, {"timestamp": /. 18:. /}, {"timestamp": /. 00:.*/} ]})

This returns what I expect. However, I can't get this to work in my Node.js server.

function getChartData_7d(callback) {
    MongoClient.connect(mongoURL, function(error, client) {
        if (error) {
            throw err;
        }

        var db = client.db('WeatherDB');
        var collection = db.collection('AverageTPH');

        var query = {
            $or:[
                {timestamp: /.* 06:.*/}, 
                {timestamp: /.* 12:.*/}, 
                {timestamp: /.* 18:.*/}, 
                {timestamp: /.* 00:.*/}
            ]
        };

        /*
        ** Even this query doesn't return anything
        */
        var query = {
            timestamp: /.* 06:.*/ 
        };

        /*
        ** But this does...
        */
        var query = {};

        var options = {
            "limit": 7
        };

        /*
        ** Get a reading 4 times a day at 06:xx, 12:xx, 18:xx, 00:xx for 7 days...
        */
        collection.find(query, options).sort({timestamp: -1}).toArray((error, items) => {
            if (error) {
                throw error;
            }

            return callback(items);
        });

        client.close();
    });
}

I've looked at examples and read the MongoDB manual but I'm scratching my head trying to get this to work. Any help would be much appreciated.

OK, I've found the solution. As there is little useful documentation and examples that I could find, I've dumped MongoDB and installed Postgres instead, works like a charm!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM