Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 449
Nasser Torabzade Avatar asked Jan 12 '14 15:01

Nasser Torabzade


People also ask

How does MongoDB generate ObjectId?

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. The 5 byte "random value" does not appear to be random.

What is ObjectId in node JS?

ObjectID() id (string) – Can be a 24 byte hex string, 12 byte binary string or a Number.

How is ObjectId generated?

ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document. ObjectID can be considered globally unique for all practical purposes. ObjectID encodes the timestamp of its creation time, which may be used for queries or to sort by creation time.

What is ObjectId in MongoDB?

An ObjectId is a 12-byte BSON type having the following structure − The first 4 bytes representing the seconds since the unix epoch. The next 3 bytes are the machine identifier. The next 2 bytes consists of process id. The last 3 bytes are a random counter value.


1 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}   ); }; 
like image 118
caub Avatar answered Oct 08 '22 06:10

caub