![](/img/trans.png)
[英]NodeJS, using MongoDB Native driver, how do I convert ObjectID to string
[英]How to convert a string to ObjectId in nodejs mongodb native driver?
使用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
var ObjectID = require('mongodb').ObjectID; // convert string to ObjectID
在 mongodb 中将var ObjectID = require('mongodb').ObjectID; // convert string to ObjectID
然后我可以在 nodejs mongodb 本机驱动器中将字符串转换为 ObjectId。
参考访问http://mongodb.github.io/node-mongodb-native/2.2/api/ObjectID.html
您可以在聚合管道中使用$toObjectId
类似的东西:
db.CollectionWithStringId.aggregate([
{$addFields: {
_id: { $toObjectId: "$_id" }
}}
])
来源: https : //docs.mongodb.com/manual/reference/operator/aggregation/toObjectId/
我的 mongodb 版本:4.9.1(nodejs)
你只需要:
import { Collection, ObjectId } from "mongodb";
然后例如删除一个文档,您只需:
return await collection.deleteOne({ _id: new ObjectId(id)});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.