将字符串转换为 MongoDB 中的 ObjectID

将字符串转换为 MongoDB 中的 ObjectID

问题描述:

我正在使用 Codeigniter 和 MongoDB 开发 API.在数据库的某些部分中,我以 ObjectID 格式保存了图像的 ID而不是字符串.现在我得到了一个字符串格式的 ID,我需要使用它来查询数据库.

I am developing an API using Codeigniter and MongoDB. In some parts of the database I have saved the ID of an image in ObjectID format instead of a string. Now I got an ID in string format and I need to query the database using it.

如何将字符串转换"为 ObjectID 以便进行查询?

How can I "convert" a string to an ObjectID so that I can do the query?

从这里:

34234234234234234234

为此:

ObjectID("34234234234234234234")

更新

我找到了解决方案.就这样做 new MongoId('34234234234234234234');

I found a solution. Just do this new MongoId('34234234234234234234');

使用猫鼬:

var mongoose = require('mongoose');
var objectId = mongoose.Types.ObjectId('569ed8269353e9f4c51617aa');

使用本机驱动程序(https://stackoverflow.com/a/21076589/3377073)

var ObjectId = require('mongodb').ObjectId;
doc._id = new ObjectId(doc._id); // wrap in ObjectID