#querying

3 messages · Page 1 of 1 (latest)

cold cosmos
#

I want to add the ability to query properties by the for_sale and for_rent fields

export const get = query({
    args: {
        type: v.optional(v.union(v.literal('for-sale'), v.literal('for-rent')))
    },
    handler: async (ctx) => {
        const properties = await ctx.db.query('properties').collect();
wanton crescentBOT
#

Hi @cold cosmos. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can add a filter to your query to filter properties based on the for_sale and for_rent fields. You can use the v.union function to allow the type argument to accept either 'for-sale' or 'for-rent'. Then, in your handler function, you can use the filter method on the query to filter properties based on the type argument.

Here's how you can modify your code:

export const get = query({
    args: {
        type: v.optional(v.union(v.literal('for-sale'), v.literal('for-rent')))
    },
    handler: async (ctx, args) => {
        let propertiesQuery = ctx.db.query('properties');
        
        if (args.type) {
            propertiesQuery = propertiesQuery.filter((q) => 
                args.type === 'for-sale' ? q.eq(q.field('for_sale'), true) : q.eq(q.field('for_rent'), true)
            );
        }

        const properties = await propertiesQuery.collect();
        // rest of your code
    }
});

In this code, if type is 'for-sale', the query will return properties where for_sale is true. If type is 'for-rent', it will return properties where for_rent is true. If type is not provided, it will return all properties.

Please note that this assumes for_sale and for_rent are boolean fields in your 'properties' table. If they are not, you may need to adjust the filter condition accordingly.

For more information on how to use queries in Convex, you can refer to the Convex documentation on query functions (https://docs.convex.dev/functions/query-functions).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: