简体   繁体   中英

cannot convert ObjectId to String in MongoDb forEach function

I'm trying to process data in mongodb between different collection using cursor.forEach.

The tool is DataGrip 2021.3.1 and the MongoDB server version is 4.4.9 .

The statement is like below:

 db.reward.find({type: "Test"}).forEach( function (p) { db.reward_order.find({rewardId: p._id.valueOf()}).forEach( function (order) { print(order.status) } ); } );

I check each reward id in reward order collection and print the order status.

The problem is, the p._id is an ObjectId while the rewardId field in reward_order collection is a string, so I have to convert to String by invoking p._id.valueOf() by following this post https://stackoverflow.com/a/46668537/6228210 . but it does not work for me.

Error message:

TypeError: invokeMember (valueOf) on org.bson.types.ObjectId@5d2a6048 failed due to: Unknown identifier: valueOf
TypeError: invokeMember (valueOf) on org.bson.types.ObjectId@5d2a6048 failed due to: Unknown identifier: valueOf
at user_script:46:67
at _ex (user_script:42:25)
at Cursor.forEach (all-standalone.js:155221: ...

Update on Jun 24:

I tried a few alternatives found from SO and some of them can achieve the effect and some not. Hope it helps anyone who are stuck with similar problem.

I'm quite confused why mongo syntax is so inconsistent with the official doc at here , appreciate if anyone could help shed light on this. Thanks. I will also dig more later.

provided a as ObjectId, here is the test result in mongosh and DataGrip respectively:

mongosh

## This works well.
> a.toString()
00000001fbc548c26669b869
> typeof a.toString()
string

## This returns still an ObjectId, not String.
> a.valueOf()
ObjectId("00000001fbc548c26669b869")
> typeof a.valueOf()
object

## It just does not work, don't know why.
> a.str

> typeof a.str
undefined

DataGrip

none of above ways work in DataGrip. currently the only trick that works is concat the ObjectId with and empty string, like:

print(p._id + '');

try this. hope it may help you.

 db.reward.find({type: "Test"}).lean().forEach( function (p) { db.reward_order.find({rewardId: p._id}).forEach( function (order) { print(order.status) } ); } );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM