0

Inside of the command line I can display a Mongodb collection with db.collection.find(), but I can't find the equivalent to that for a get request in Node. Here's my Express route:

app.get('/latest/imagesearch', (req, res) => {
  MongoClient.connect(mLab, function(err, db) {
    if (err) {
        console.log("Unable to connect to server", err);
    } else {
        console.log("Connected to server");

        var collection = db.collection('links');

        // res.send(collection.find());

        db.close();
    }
  });
});

And the database info:

{ "_id" : ObjectId("58cf0485a3c6700a3eb8b373"), "term" : "dogs", "when" : 1489962117592 }
2
  • What console log statements are printed when you run the express server and go to the localhost:3000/latest/imagesearch url? Commented Mar 20, 2017 at 1:54
  • Try: res.send( db.collection('links').find()) Commented Mar 20, 2017 at 2:04

1 Answer 1

1

After creating the collection object, you can call collection.find:

app.get('/latest/imagesearch', (req, res) => {
  MongoClient.connect(mLab, function(err, db) {
    if (err) {
      console.log("Unable to connect to server", err);
      return res.send("Unable to connect to server");
    } else {
      console.log("Connected to server");
      var collection = db.collection('links');
      collection.find().toArray(function(err, docs) {
        return res.json(docs);
      });
    }
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.