将字符串转换为 MongoDB 中的 ObjectID [英] Convert string to ObjectID in MongoDB
本文介绍了将字符串转换为 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
这篇关于将字符串转换为 MongoDB 中的 ObjectID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文