我在一个环境中使用mongodb本机驱动程序,nodejs
我需要将一个id
字符串转换为ObjectId以在我的更新查询中使用它,我该怎么做?
使用ObjectId(nodejs驱动程序文档)
当您有一个表示BSON ObjectId的字符串(例如从Web请求接收)时,您需要将其转换为ObjectId实例:
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} ); };
var {ObjectId} = require('mongodb'); // or ObjectID Not Working
正如@caubub所提到的那样对我不起作用.
但是当我var ObjectID = require('mongodb').ObjectID; // convert string to ObjectID
在mongodb中使用时,我能够在nodejs mongodb native drive中将字符串转换为ObjectId.
如需参考,请访问http://mongodb.github.io/node-mongodb-native/2.2/api/ObjectID.html