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
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}
);
};
-
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– caubCommented 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
-
-
@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– caubCommented Mar 15, 2018 at 14:29
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
-
3To clarify, ES6 object destructuring (
{ ObjectID } = require...
) only works on Node version 6.0 and above, older versions require the old syntax.– MacKCommented May 17, 2018 at 10:45 -
3ObjectID (with capital "D") is deprecated. Use ObjectId (lowercase "d") instead. (source:
@types/bson
package) Commented Apr 5, 2020 at 10:42
I solved this using the following:
return collection.findOneAndUpdate(
{_id: ObjectId.createFromHexString(id)},
{$set: doc},
{returnOriginal: false}
);
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/
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)});
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
}