Search code examples
node.jstypescriptmongodbnestjstypeorm

Typeorm Mongodb Repository find method doesn't work


I'm working with typeorm + mongodb in one of my projects, and was reading the docs, in which I needed to do a find checking against a string array.

This should be simply achievable with a query {where: { property: {$in: myStringArray}}}

As documentation explains: enter image description here

But for some reason, whenever I try to use this on code:

enter image description here enter image description here

as I went through the types inside my code editor, it says that were expect strings or typeorm find methods(such as In, LessThan, ..., but those don't work with mongodb), but not objects.

Why the heck there's these suggestions on typeorm documentation, but inside code it looks different?

Anyone knows how to overcome this?


Solution

  • Update: This looks like an error that is still open in Typeorm project.

    I found two ways of overcoming it. You can either:

    Solution 1, add @ts-ignore:

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    

    With this, typescript won't complain about the typing, and will work as expected. You must use right above your where clause, such as:

    const assetsExists = await assetRepository.find({
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          where: {
            sourceId: { $in: assetIds },
          },
        })
    

    Solution 2, you can cast it to unknown and then to string(ugly af, but it works)

    const assetsExists = await assetRepository.find({
          where: {
            sourceId: { $in: assetIds } as unknown as string,
          },
        })
    

    Personally I'm moving with the solution 1, and from what I check from open issues, this been appearing quite a lot, so if you have this problem, maybe consider one of the two approaches. :)