0

I am using NestJS/mongoose in my project. All straightforward filters are working fine, but when I try to filter with nested data. eg.

interface abc{
    id: mongoose.Schema.Types.ObjectId
    name: string
}
interface pqr{
    prop1: string
    prop2: string
    prop3: abc
    prop4: abc
}
interface xyz {
    key1: string
    key2: string
    key3: pqr 
}

While querying {"key3.prop3.id":new ObjectId("62ceb429804e78434d21af4e")} responds with the correct result inside NestJS project. but if I query through a network request, I can't send ObjectID as it gets covered into a string and as a result, it responds with an empty array. Is there any way to match both ObjectId as well as string for the query. If any way to add an operator to change it to ObjectId will also be acceptable like

{"$or":[{"key3.prop3.id":{"$oid":"62ceb429804e78434d21af4e"}},...]}

will gets chnaged into

{"$or":[{"key3.prop3.id":new ObjectId("62ceb429804e78434d21af4e")},...]}

Sahyog Vishwakarma
  • 330
  • 1
  • 2
  • 11

1 Answers1

0

I think that you should first convert the request string to mongoId/ObjectId using the next lines of code.

const { ObjectId } = require('mongodb');
const _id = ObjectId(req.id); // if your sting is by the name id and inside the request object

You can find more about this, in this stackoverflow question

air_ioannis
  • 146
  • 1
  • 6
  • I appreciate your answer, but the filter will come from a frontend/UI and it may or may not have those keys for filtering documents. also, those could be anywhere in the filter object which is the main issue. – Sahyog Vishwakarma Jul 14 '22 at 11:14