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?
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.
ObjectID() id (string) – Can be a 24 byte hex string, 12 byte binary string or a Number.
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.
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.
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} ); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With