0

I have a mongodb collection called lights and a document in this collection looks like,

{
    "_id": "50eea4a53004cc6233d12b02",
    "Physicalentity": "Light",
    "Sensor": "Tinkerforge",
    "Unit": "Lux",
    "value": "47.2",
    "time": "12:23:17",
    "date": "10.01.2013"
  },

I would like to retrieve a document based on the time, hence to accomplish this, I wrote the following:

    app.get('/lights/:time', function(req, res) {
    var time = req.params.time;
console.log('Retrieving value: ' + time);
db.collection('lightsensor', function(err, collection) {
        collection.findOne({'time':new BSON.ObjectID(time)}, function(err, item) {
            res.send(item);
        });
    }); 
    });

But when I enter the URL http://localhost:3000/lights/12:23:17

I get Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

Where exactly is the problem?

And is it possible to enter a time and allow mongodb, to find the document which has the closest time specified in the URL.

For instance, I enter http://localhost:3000/lights/12:23:20

Which is not in my collection but a document with time 12:23:17 exists.

How can I tell mongodb to find the documents containing a value closest to the parameter passed.

Cœur
  • 37,241
  • 25
  • 195
  • 267
spaniard89
  • 307
  • 1
  • 6
  • 18
  • time is not an ObjectId, so it's failing to convert. – WiredPrairie Jan 21 '13 at 14:32
  • MongodB doesn't have support for what you're trying to do natively (except for 2D Geospatial indexes). You may have to do a range query and then sort the results based on time span (and limit those results). Feels a bit clunky though, yet this would be a challenge for most databases. – WiredPrairie Jan 21 '13 at 14:49

1 Answers1

0

First of all you should use a Date for the time not a string. I suggest replacing date and time fields with a single datetime field using a javascript date object as it then makes it possible for you to use dates in queries on mongodb. If you need to match on something like the time in your url you just have to map from that string to a date object so you can query for the document.

christkv
  • 4,370
  • 23
  • 21