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

Javascriptnode.jsMongodb

Javascript Problem Overview


I'm using mongodb native driver in a nodejs environment and I need to convert an id string to ObjectId to use it in my update query, how can I do this?

Javascript Solutions


Solution 1 - Javascript

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}
  );
};

Solution 2 - Javascript

var {ObjectId} = require('mongodb'); // or ObjectID Not Working

as mentioned by @caubub won't work for me.

But when I use var ObjectID = require('mongodb').ObjectID; // convert string to ObjectID in mongodb then I am able to convert string to ObjectId in nodejs mongodb native drive.

For reference visit to http://mongodb.github.io/node-mongodb-native/2.2/api/ObjectID.html

Solution 3 - Javascript

You can use $toObjectId in agregation pipeline something like that :

db.CollectionWithStringId.aggregate([
{$addFields: {
    _id: { $toObjectId: "$_id" }
}}

])

source :https://docs.mongodb.com/manual/reference/operator/aggregation/toObjectId/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNasser TorabzadeView Question on Stackoverflow
Solution 1 - JavascriptcaubView Answer on Stackoverflow
Solution 2 - JavascriptVIKAS KOHLIView Answer on Stackoverflow
Solution 3 - Javascriptclement boxView Answer on Stackoverflow