0

I'm attempting to build a simple CRUD application using express and mongodb. My GET request for all database entries is working and my POST request is working but I can't seem to figure out the problem with my GET request for individual entries.

Server.js GET request:

app.get('/api/:id', function (req, res) {
  var id = req.params.id;

  db.collection('api').findOne({_id: id}, (err, result) => {
    if (err){
      res.sendStatus(404);
      return console.log(err);
    }
    res.redirect('/');
    return console.log(result);

  });

});

When I type 'url/api/593555074696601afa192d7f' which is an ID I know exists the console.log is returning null, I'm not sure if I'm doing something wrong?

  • Try to turn debug mode on and check the exact query. Seems you are directly using MongoDB drivers for node. http://mongodb.github.io/node-mongodb-native/2.0/tutorials/logging/#setting-log-level:3f3af53408cff75953b33723c0b061bb – Anand Jun 05 '17 at 16:50
  • Thanks, the output is at least 1000 lines, is anything in particular I should be looking for? –  Jun 05 '17 at 16:56
  • Possible duplicate of [node.js mongodb select document by \_id node-mongodb-native](https://stackoverflow.com/questions/4902569/node-js-mongodb-select-document-by-id-node-mongodb-native) – s7vr Jun 05 '17 at 17:18

1 Answers1

0

You should pass ObjectID instance in the query.

let ObjectID = require("mongodb").ObjectID;

app.get('/api/:id', function (req, res) {
  var id = req.params.id;

  db.collection('api').findOne({_id: ObjectID(id)}, (err, result) => {
    if (err){
      res.sendStatus(404);
      return console.log(err);
    }
    res.redirect('/');
    return console.log(result);

  });

});

Give Mongoose a try. It might be of help if your models get complex.

Anand
  • 1,335
  • 1
  • 12
  • 20
  • Awesome, that worked, thank you! I've dabbled with mongoose but I wanted to get a better understanding of the base technologies first and then I'm going to start introducing things like mongoose so I can appreciate how much they help. –  Jun 05 '17 at 17:32