0

I have a collection of users, and a collection of user orders. When I retrieve a user, I add all of the orders to the returned structure to make the client-side simpler. However, I am using NextJS, and thus objects like Date and ObjectId have to be toString'd before reaching the client side. I did these type conversions and linking between users and orders manually in JS, but doing so in the Mongo driver would clean my code quite a lot. So now I am looking at aggregation, and it was simple enough to add the orders, however I can't for the life of me figure or google how to refer to the _id field (or others) of the orders to convert it to a string.

This is how the aggregation looks:

[
  {
    $lookup: {
      from: 'orders',
      localField: 'id',
      foreignField: 'user_id',
      as: 'orders',
    },
  },
  { 
    $project: {
      _id: { $toString: '$_id' },
      name: 1,
      'orders._id': { $toString: '???' },
      'orders.order': 1,
    },
  }
]

What do I put in the 'orders._id' part? I tried so many combinations, but the best I got is Mongo complaining I am trying to convert an array to a string.

Given a user

{ _id: ObjectId('objectId1'), id: 'id', name: 'name' }

And an order

{ _id: ObjectId('objectId2'), user_id: 'id', order: { ... } }

The end result should be

{ _id: 'objectId1', name: 'name', orders: [ { _id: 'objectId2', order: { ... } } ] }

1 Answer 1

1

Since orders is an array, orders._id is an array of all of the _id fields from the objects in orders.

In order to modify each of the elements you will need to either unwind the array, project, and then group; or use reduce, map, or something similar to modify each element.

Sign up to request clarification or add additional context in comments.

2 Comments

I find it odd, because normally in the projection there is no issue referring to embedded document fields, but it sounds like doing any transformation on them ($toString in this case) would require actual mapping. Thanks for the answer
Just to help you understand, try projecting 'orders._id': "$orders._id" to see what that actually returns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.