user2503048
user2503048

Reputation: 1041

MongoDB - $toString'ing a field of an embedded document array in an aggregation

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: { ... } } ] }

Upvotes: 0

Views: 442

Answers (1)

Joe
Joe

Reputation: 28326

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.

Upvotes: 1

Related Questions