Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...