将字符串转换为 MongoDB 中的 ObjectID

问题描述 投票:0回答:10

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

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

从此:

34234234234234234234

对此:

ObjectID("34234234234234234234")
codeigniter mongodb
10个回答
63
投票

使用猫鼬:

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

46
投票

您只需要从 mongo 中获取 ObjectId 函数即可。

ObjectId = require('mongodb').ObjectID;

然后你就可以这样使用它:

ObjectId("34234234234234234234")

6
投票

如果您使用Meteor

var id = new Mongo.ObjectID("34234234234234234234");

4
投票

您现在可以在 mongodb 4.0 及更高版本上将字符串转换为 objectId。有从字符串 id 转换为 objectId 的新功能

在这里您可以查看文档$toObjectId


1
投票

如果您在聚合中,您可以使用以下内容:

{
   $toObjectId: <expression>
}

这是 :

的快捷方式
{ $convert: { input: <expression>, to: "objectId" } }

来自 mongodb 文档


0
投票

或更好的使用

var mongodb = require(‘mongodb’); //this might have been defined at the beginning of your code.
//now use it
query = {_id:mongodb.ObjectId('569ed8269353e9f4c51617aa')};

其余的都一样。


0
投票

(摘自问题)


我找到了解决办法。只需这样做:

new MongoId('34234234234234234234');

0
投票

猫鼬中如果没有“new”,则无法调用类构造函数ObjectId

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

-1
投票
import { ObjectId } from 'mongodb'
const query  = {"_id":ObjectId(req.params.productId)}

-4
投票

mongo数据库版本v3.6.3

如何将字符串输入保存到 MongoDB ObjectId 在快速控制器代码上

const mongoose = require('mongoose');
var ObjectId = require('mongodb').ObjectId;
user: mongoose.Types.ObjectId(req.body.user)
console.log(user, typeof(user))

© www.soinside.com 2019 - 2024. All rights reserved.