Sunday 21 May 2017

findOne by id using ObjectID or String?

If I have the id string with the document's id I want to lookup in a findOne

Should I use the plain id string, or convert it using the built in ObjectID?

const convertToObjectId = require('mongodb').ObjectID;

const id = "0edfb8648d842842d282dec9";
let userId = id; // userId = new convertToObjectId(id);

db.collection('users').findOne({ userId }, function (err, user) {
  console.log(err);
  // no error in both case
  console.log(user);
  // user is the document when id is plain string
  // user is null when it is an ObjectID
});

findOne always returns null when I convert the string id to ObjectID.



via vrotos

No comments:

Post a Comment