Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
183
rated 0 times [  188] [ 5]  / answers: 1 / hits: 83424  / 11 Years ago, sun, january 12, 2014, 12:00:00

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?


More From » node.js

 Answers
20

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

[#73225] Friday, January 10, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
wilson

Total Points: 27
Total Questions: 93
Total Answers: 93

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
wilson questions
Tue, Aug 9, 22, 00:00, 2 Years ago
Wed, May 11, 22, 00:00, 2 Years ago
Wed, May 20, 20, 00:00, 4 Years ago
Wed, May 13, 20, 00:00, 4 Years ago
;