I have JSON data like you see below in a collection called 'English', for which I'm setting up a REST api with a nodejs app using the MongoDB driver. If I do the following, I get all the JSON data returned in the browser.
app.get('/sentences', function (req, res){
db.collection('english', function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
})
However, when I try to go to /sentences/1
to get one record, the app is freezing (the half-moon in the browser tab turns slowly) and there's no error logged. Is there something wrong with how I'm doing this findOne?
app.get('/sentences/:id', function(req,rest){
var query = { 'question' : req.params.id };
console.log(query);
console.log('query');
db.collection('english', function(err, collection) {
collection.findOne(query, function(err, item) {
console.log(err);
res.send(item);
});
});
});
JSON data
[
{
"_id": "526c0e21977a67d6966dc763",
"question": "1",
"uk": "blah blah blah",
"us": "blah blah balh"
},
{
"_id": "526c0e21977a67d6966dc764",
"question": "2",
"uk": "Tom went outside for a fag. I think he smokes too much!",
"us": "Tom went outside for a cigarette. I think he smokes too much!"
},
{
"_id": "526c0e21977a67d6966dc765",
"question": "3",
"uk": "Do you fancy going to the cinema on Friday?",
"us": "How about going to the movies on Friday"
}
]
Update
What's happening is that the app is eventually timing out and I get a No data received
message in the browser.
The findOne() method returns the first occurrence in the selection. The first parameter of the findOne() method is a query object. In this example we use an empty query object, which selects all documents in a collection (but returns only the first document).
Description. the collection method `findOne` is marked as deprecated since 2.0, while other driver implementations do offer it with no deprecation marks.
MongoDB – FindOne() Method. The findOne() method finds and returns one document that matches the given selection criteria. If multiple documents satisfy the given query expression, then this method will return the first document according to the natural order which reflects the order of documents on the disk.
find() returns a cursor whereas findOne() returns the exact document. It is faster to use find() + limit() because findOne() will always read + return the document if it exists. find() just returns a cursor (or not) and only reads the data if you iterate through the cursor.
It is late but will be helpful others.
var id = new require('mongodb').ObjectID('58fcf02b1ab5de07e2a1aecb');//req.params.id
db.collection('users').findOne({'_id':id})
.then(function(doc) {
if(!doc)
throw new Error('No record found.');
console.log(doc);//else case
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With