How to convert a string to ObjectId in nodejs mongodb native driver?

with ObjectId (nodejs driver doc)

When you have a string representing a BSON ObjectId (received from a web request for example), then you need to convert it to an ObjectId instance:

const {ObjectId} = require('mongodb'); // or ObjectID 
// or var ObjectId = require('mongodb').ObjectId if node version < 6

const updateStuff = (id, doc) => {
  // `ObjectId` can throw https://github.com/mongodb/js-bson/blob/0.5/lib/bson/objectid.js#L22-L51, it's better anyway to sanitize the string first
  if (!ObjectId.isValid(s)) {
    return Promise.reject(new TypeError(`Invalid id: ${id}`));
  }
  return collection.findOneAndUpdate(
    {_id: ObjectId(id)}, 
    {$set: doc}, 
    {returnOriginal: false}
  );
};

Leave a Comment