67

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?

6 Answers 6

97

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}
  );
};
6
  • thanks, you're right about my use case. but if I generate _id in client side, isn't it required to check its uniqueness in my collection? I supposed that check is more expensive than type casting in server side, what do you think? Commented Jan 12, 2014 at 15:52
  • 1
    "If the value were not unique, the insert would fail" from docs.mongodb.org/manual/reference/method/db.collection.insert, and I don't know about performances of each method, but ObjectIds are just 24bytes hash, it's up to your implementation
    – caub
    Commented Feb 14, 2014 at 0:49
  • Hello, @caub Thanks for your valuable answer. I am kinda newbie in Angular 2/4 and MongoDb. In my application, i am using Angular 2, LoopBack and MongoDb. I am not sure where this chunk of code should be added!! Shall it be added in Angular typescript file or in LoopBack server file? Can you guide me on this. I am completely stuck at this point of time. If i am adding this code in typescript file then i am getting below error: Module not found: Error: Can't resolve 'mongodb' Commented Mar 7, 2018 at 6:37
  • This logic is on the server, It's using mongodb driver package (nodejs only)
    – caub
    Commented Mar 7, 2018 at 9:41
  • @PrasadKaiche ObjectId alone could be used on client or server but if you do, be careful on how those ids get generated to make sure they are as much unique as possible
    – caub
    Commented Mar 15, 2018 at 14:29
11
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

2
  • 3
    To clarify, ES6 object destructuring ({ ObjectID } = require...) only works on Node version 6.0 and above, older versions require the old syntax.
    – MacK
    Commented May 17, 2018 at 10:45
  • 3
    ObjectID (with capital "D") is deprecated. Use ObjectId (lowercase "d") instead. (source: @types/bson package) Commented Apr 5, 2020 at 10:42
3

I solved this using the following:

return collection.findOneAndUpdate(
    {_id: ObjectId.createFromHexString(id)}, 
    {$set: doc}, 
    {returnOriginal: false}
  ); 

1

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/

1
  • Doesn't look like this works with v6.8.0. Commented Jul 29 at 11:21
0

My mongodb version: 4.9.1 (nodejs)

You just have to:

import { Collection, ObjectId } from "mongodb";

And then for example delete a document, you just:

return await collection.deleteOne({ _id: new ObjectId(id)});
0

Using Node.js and MongoGB v6.5.0, here's another solution for those who are still struggling with this issue;

I had the same problem, looping over an array with id's, adding the specific id record to an array to be used to update Mongo.

I tried;

let ids = element.ids //ids are already and array in element

 ids.forEach(id => {
   let objId = ObjectId(id)
   if (!objectIds.includes(objId)) {
     objectIds.push(objId) 
   }
});

... but no luck and after some playing around, I kept the above forEach function, but just before updating Mongo, I did this:

const NewObjectIds = objectIds.map(id => ObjectId.createFromHexString(id));

const result = await myCollection.updateMany(
  { _id: { $in: NewObjectIds } },
  { $set: { symbolUsed: true } }
);

and worked like a charm!! Here's the output on the Update

{
  acknowledged: true,
  modifiedCount: 14,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 14
}
1
  • Try to concentrate in answering the question
    – yeya
    Commented Apr 14 at 17:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.