alexsk / mongoose-intl

Mongoose schema plugin for multilingual fields
MIT License
74 stars 31 forks source link

$match on aggregate #32

Closed cybercoder closed 4 years ago

cybercoder commented 4 years ago

How i can use dynamic locale when aggregate? This is my aggregate expression:

    let a = PostModel.aggregate([
      {
        $lookup: {
          from: 'users',
          localField: 'author',
          foreignField: '_id',
          as: 'author',
        },
      },
      // {
      //   $match: () => !!title[`${locale}`],
      // },
      {
        $unwind: '$author',
      },
      {
        $project: {
          'author.email': 1,
          'author._id': 1,
          'author.firstName': 1,
          'author.lastName': 1,
          'author.avatar': 1,
          coverPhoto: { $arrayElemAt: ['$attachments', 0] },
          title: `$title.${locale}`,
          intro: { $substr: [`$body.${locale}`, 0, 100] },
          location: 1,
          tags: 1,
          favs: 1,
          createdAt: 1,
          updatedAt: 1,
        },
      },
    ]);

I need to fetch only posts of one locale if that translation exists. The commented section not works.

SelvinM commented 4 years ago

Maybe you already figured something out but basically, you can't. However, there's a workaround. You can iterate the object you get from the aggregate and inside the iteration you can transform each item of the object to a mongoose Document like so:

const transformedDocument = new PostModel({...post})

cybercoder commented 4 years ago

Maybe you already figured something out but basically, you can't. However, there's a workaround. You can iterate the object you get from the aggregate and inside the iteration you can transform each item of the object to a mongoose Document like so:

const transformedDocument = new PostModel({...post})

Thanks for your reply, I needed to return null when there was no translation for the requested item, So i did handle that manually without using this plugin. This plugin will return default locale contents when there is no translation.

Regards.