如何将一个string转换为nodejs mongodb本地驱动程序中的ObjectId?
我在一个nodejs
环境中使用mongodb本地驱动程序 ,我需要将一个id
string转换为ObjectId使用它在我的更新查询中,我该怎么做?
用ObjectId ( nodejs driver doc )
当你有一个表示BSON ObjectId的string(例如从web请求中接收到),那么你需要把它转换成一个ObjectId实例:
collection.findOneAndUpdate( {_id: safeObjectId(id)}, {$set: newDoc}, {returnOriginal: false} ) .then(console.log, console.error)
与safeObjectId
定义为:(避免可能的exception )
const {ObjectId} = require('mongodb'); // or ObjectID // or var ObjectId = require('mongodb').ObjectId if node version < 6 const safeObjectId = s => ObjectId.isValid(s) ? new ObjectId(s) : null;
var {ObjectId} = require('mongodb'); // or ObjectID Not Working
正如@caubub所提到的那样对我不起作用。
但是当我使用var ObjectID = require('mongodb').ObjectID; // convert string to ObjectID
var ObjectID = require('mongodb').ObjectID; // convert string to ObjectID
mongodb中的var ObjectID = require('mongodb').ObjectID; // convert string to ObjectID
,然后我可以将string转换为nodejs mongodb本地驱动器中的ObjectId。
有关参考访问http://mongodb.github.io/node-mongodb-native/2.2/api/ObjectID.html