Home Ask Login Register

Developers Planet

Your answer is one click away!

Joao February 2016

db.collection findOne by id runs but doesn't return

i'm using the node mongo db native module and i'm having difficult with the findOne.

When i run:

let collection = db.collection('eventschemas')

collection.find({}).toArray(function(error, result) {
  if (error) console.log(error);
  console.log(result);
});

The result will be:

[ { _id: 56b644a1bc8f66ce59322b38,
    type: 'events',
    attributes: 
     { hiw: [Object],
       title: 'Pub Crawl',
       'meeting-point': 'Ponto de encontro',
       information: '1h de Open Bar',
       'women-price': 40,
       'men-price': 60,
       end: Sat Feb 13 2016 17:08:00 GMT-0200 (BRST),
       start: Sat Feb 13 2016 17:07:59 GMT-0200 (BRST),
       'updated-at': Sat Feb 06 2016 17:08:54 GMT-0200 (BRST),
       'created-at': Sat Feb 06 2016 17:08:17 GMT-0200 (BRST),
       'is-active': true },
    __v: 0 } ]

I just have one event, so it's the right result. But when i run:

let collection = db.collection('eventschemas')

collection.findOne({ _id: '56b644a1bc8f66ce59322b38' }, function(error, result) {
  if (error) console.log(error);
  console.log(result);
});

The result will be null, what doesn't make sense. Am i missing something?

Thanks.

Answers


chridam February 2016

Try wrapping the _id string in ObjectID():

var ObjectID = require('mongodb').ObjectID,
    id = new ObjectID('56b644a1bc8f66ce59322b38'); // wrap in ObjectID

let collection = db.collection('eventschemas')

collection.findOne({ _id: id }, function(error, result) {
    if (error) console.log(error);
    console.log(result);
});

Post Status

Asked in February 2016
Viewed 3,717 times
Voted 14
Answered 1 times

Search




Leave an answer


Quote of the day: live life