[英]Find() with array of ids not working
I have this route that I access from an AJAX GET call. 我有可以通过AJAX GET调用访问的路由。
router.get("/index/fill/:id", function(req, res){
var idArray = req.params.id;
console.log(idArray); // OUTPUT = "4ed3ede8844f0f351100000c", "4ed3f117a844e0471100000d"
User.find({'_id': {$in: idArray}}, function(err, foundUsers){
console.log(foundUsers);
});
});
Before the start of the find proccess the code throws me this error: 在开始查找过程之前,代码将向我抛出此错误:
Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
But when i use typeof
in idArray[i]
it says that it is a string. 但是当我在
idArray[i]
使用typeof
,它说这是一个字符串。
What am I doing wrong here? 我在这里做错了什么?
I think this is because your ids
should be of type ObjectId(...)
我认为这是因为您的
ids
应该是ObjectId(...)
类型
Make sure you have imported ObjectId = require('mongodb').ObjectId;
确保已导入
ObjectId = require('mongodb').ObjectId;
You can try something like this: 您可以尝试如下操作:
router.get("/index/fill/:id", function (req, res) {
var idArray = req.params.id;
idArray = idArray.map(id => ObjectId(id));
User.find({'_id': {$in: idArray}}, function (err, foundUsers) {
console.log(foundUsers);
});
});
or can also check new ObjectId.createFromHexString(id)
in the map function if for some reason the straightforward object id creation doesn't work 或者也可以在地图函数中检查
new ObjectId.createFromHexString(id)
,如果由于某种原因直接创建对象ID无效
Regarding the error: 关于错误:
Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
传入的参数必须是12个字节的单个字符串或24个十六进制字符的字符串
It is thrown because find
is expecting some ObjectId
structure, which looks something like this: {'_id':'somehexof24char123456789'}
but it doesn't find and _id
which contains a required string so it throws this error. 抛出该错误是因为
find
期望使用某种ObjectId
结构,该结构看起来像这样: {'_id':'somehexof24char123456789'}
但找不到,并且_id
包含必需的字符串,因此抛出此错误。
I think you can find some documentation here and here about ObjectId 我认为您可以在此处和此处找到有关ObjectId的一些文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.