jax
jax

Reputation: 38573

Can't get mongoose findById() working

From the Mongo Shell

db.messages.find({_id:ObjectId('57b12ca68ea2e15c182044f3')})

Works and prints the record to the screen.

From express http://localhost:3000/messages/57b12ca68ea2e15c182044f3

app.get('/messages/:id', function (req, res) {
  console.log('Searching user with ID: ' + req.params.id);

  // message is always null, have tried without "mongoose.Types.ObjectId" but it is still null
  Message.findById(mongoose.Types.ObjectId(req.params.id), function(err, message) {
    console.log('Found record');

    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify(message));
  });
});

I get a null response every time. I have tried without using ObjectId wrapper but I still get null values. The mongoDB connection is fine because I have a Message.find({}, function(err, messages) { ... } returns all the messages successfully.

What am I doing wrong?

Upvotes: 1

Views: 1489

Answers (1)

jax
jax

Reputation: 38573

Turns out that I incorrectly defined _id: String in the mongoose schema file which caused this issue. Removing the _id definition completely solves this.

Upvotes: 1

Related Questions