2

Using MongoJS: https://github.com/mafintosh/mongojs

Finds everything


    db.users.find({}, function(err,users){
        if (err) throw err;
        console.log(users);
    })

Returns the user. looks great


    [{ _id: 53f2faa6aed1689e84982b8b,
        facebook: { 
            email: 'myname@gmail.com',
            name: 'Juan Atkins',
            id: '764969936' },
        __v: 0 
    }]

When I try to find that user by his id: failed


    db.users.findOne({
        _id:  '53f2faa6aed1689e84982b8b'
    }, function(err, user) {
        if (err) throw err;
        console.log(user);
    });

returns []

I know there is data in the DB. I've tried searching by a different key (like name). Why can't it find the data?

Venkat.R
  • 7,420
  • 5
  • 42
  • 63

1 Answers1

3

you have to use ObjectId: http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html

db.users.findOne({
    _id:  new ObjectID('53f2faa6aed1689e84982b8b')
}, function(err, user) {
    if (err) throw err;
    console.log(user);
});
Jan Remunda
  • 7,840
  • 8
  • 51
  • 60
  • Good call but I tried that `ReferenceError: ObjectID is not defined` – Matthew Nolan Aug 19 '14 at 14:29
  • @MatthewNolan Then you need to define it using the function from the driver module: `var ObjectID = require('mongodb').ObjectID;` – apsillers Aug 19 '14 at 14:34
  • I'm using the wrapper mongojs. They do recommend doing something similar, but when I try it, it says it doesn't have a method ObjectJD. `db.users.findOne({ _id: mongojs.ObjectID('53f2faa6aed1689e84982b8b') }, function(err, user) { if (err) throw err; console.log(user); }); ` – Matthew Nolan Aug 19 '14 at 14:56
  • Hm, this API has different letter case: mongojs.ObjectId('523209c4561c640000000001') – Jan Remunda Aug 20 '14 at 08:06