I have been exploring ways to limit my search capabilities to specific criteria.
Let's say I have a model and some data like the following:
interface UserModel {
_id: string;
username: string;
party: UserPartyModel;
}
interface UserPartyModel {
invites: number;
rsvps: number;
}
//Test Data
{
_id: '123',
username: 'testuser',
party: {
invites: 18,
rsvps: 3
}
}
When using mongodb, queries can be made based on root properties:
db.users.findOne({_id: '123'});
db.users.findOne({username: 'testuser'});
To handle errors for properties not in the model, I created the type below:
export declare type MongoManagerFilter<T> = {
[P in keyof T]?: T[P];
};
Mongodb also allows searching within nested objects as demonstrated here:
db.users.findOne({'party.invites': 18});
However, upon utilizing the MongoManagerFilter
type, an error is triggered stating that 'party.invites'
does not exist in UserModel
.
To address this issue, a function like the one below can be employed:
function isDotStringRegExp(obj: Object, dotKey: string): boolean {
let keyData = dotKey.split('.');
let objData = obj;
for (let i = 0; i < keyData.length; i++) {
let key = keyData[i];
if (objData.hasOwnProperty(key)) {
objData = objData[key];
if (i === keyData.length - 1) {
return true;
}
}
else {
return false;
}
}
}
A new type can then be introduced for this purpose:
export declare type MongoManagerDotStringFilter<T> = {
[key: string]: (isDotStringRegExp(T, key) ? any : never);
};
Unfortunately, running the isDotStringRegExp
function within this type is currently restricted.
Is there a way to achieve this functionality?