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 retrive 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 paramater passed.
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.