Skip to main content

Detailed Explanation of Query Parameters

The cloud development data model provides powerful query capabilities, supporting complex query conditions, field selection, sorting, pagination, and relational queries. This article details various parameters and usage methods for data model query operations.

Overview of Query Parameters

The query operations of the data model primarily include the following parameters:

ParameterTypeDescriptionRequired
selectSelectParamsSpecifies the fields to returnNo
filterFilterParamsQuery filter conditionsNo
orderByOrderByParams[]Sorting conditionsNo
pageSizenumberPage size, maximum 200No
pageNumbernumberPage numberNo
getCountbooleanSpecifies whether to return the total countNo

Field Selection select

The select` parameter is used to specify the fields to be included in the query results, enabling precise control over both primary model fields and associated model fields.

✅ It is recommended to select only the required fields and relationships to reduce the response data size and improve query speed.

Return All Fields of the Primary Model

Using $master: true returns all fields of the primary model:

const {
data
} = await models.post.get({
select: {
$master: true, // Query all fields of the primary model.
},
filter: {
where: {
_id: {
$eq: _id, // It is recommended to pass the _id as data identifier for operations.
},
},
},
});

console.log(data);
// {
// "owner": "Anonymous(95fblM7nvPi01yQmYxBvBg)",
// "createdAt": 1717488585078,
// "createBy": "Anonymous(95fblM7nvPi01yQmYxBvBg)",
// "updateBy": "Anonymous(95fblM7nvPi01yQmYxBvBg)",
// "_openid": "95fblM7nvPi01yQmYxBvBg",
// "_id": "e2764d2d665ecbc9024b058f1d6b33a4",
// "title": "Hello, World👋",
// "body": "Article content...",
// "slug": "hello-world",
// "updatedAt": 1717490751944
// }

Return Specified Fields

Select specific fields by setting the field name to true:

const {
data
} = await models.post.list({
select: {
_id: true,
title: true,
updatedAt: true,
},
filter: {
where: {},
},
getCount: true,
});

console.log(data);
// {
// "records": [
// {
// "_id": "e2764d2d665ecbc9024b058f1d6b33a4",
// "title": "Hello, World👋",
// "updatedAt": 1717492882289
// }
// // ... more records
// ],
// "total": 51
// }

Return Associated Model Fields

Can query fields of associated models simultaneously:

const {
data
} = await models.post.list({
select: {
_id: true,
title: true,
updatedAt: true,
// Join query for comment data
comments: {
_id: true,
createdAt: true,
comment: true,
}, // You can also directly pass true to return all fields in the comments.
},
filter: {
where: {},
},
getCount: true,
});

console.log(data);
// {
// "records": [
// {
// "_id": "9FSAHWM9VV",
// "title": "Bonjour le Monde👋",
// "updatedAt": 1718096503886,
// "comments": [
// {
// "_id": "9FSAJF3GLG",
// "createdAt": 1718096509916,
// "comment": "This is a comment"
// }
// ]
// }
// // ... more records
// ],
// "total": 2
// }

Query Filter filter

The filter` parameter is used to specify query conditions and supports two methods: basic queries and relational queries.

Basic Query where

Basic queries are used to filter fields of the main model:

const {
data
} = await models.post.list({
filter: {
where: {
// title contains "world"
title: {
$search: "world",
},
// body is not empty
body: {
$nempty: true,
},
},
},
select: {
$master: true,
},
});

Relational Query relateWhere

Relational queries are used to filter based on the conditions of associated models:

const {
data
} = await models.post.list({
filter: {
// Query articles with comments
relateWhere: {
comments: {
where: {
comment: {
$nempty: true, // Comment content is not empty
},
},
},
},
where: {}, // Query conditions for the main model
},
select: {
$master: true,
comments: {
comment: true,
},
},
});

Composite Query Example

When you need to use AND/OR relationships, you can use the $and and $or operators in the where parameter.

If you use the $and and $or operators, you need to place them in an array:

const {
data
} = await models.post.list({
filter: {
where: {
$and: [{
// The title contains "technology" or "tutorial"
$or: [{
title: {
$search: "technology"
}
},
{
title: {
$search: "tutorial"
}
}
]
},
{
// Creation time within the last 30 days
createdAt: {
$gte: Date.now() - 30 * 24 * 60 * 60 * 1000
}
},
{
// Status is Published
status: {
$eq: "published"
}
}
]
},
},
select: {
_id: true,
title: true,
createdAt: true,
status: true,
},
});

Query Operators

OperatorDescriptionExample
$eqEquals{status: {$eq: "active"}}
$neNot equal to{status: {$ne: "deleted"}}
$gtGreater than{score: {$gt: 80}}
$gteGreater than or equal to{age: {$gte: 18}}
$ltLess than{price: {$lt: 100}}
$lteLess than or equal to{discount: {$lte: 0.5}}
$inIn an array{category: {$in: ["tech", "news"]}}
$ninNot in an array{status: {$nin: ["deleted", "banned"]}}
$andLogical AND{$and: [{age: {$gte: 18}}, {status: {$eq: "active"}}]}
$orLogical OR{$or: [{priority: {$eq: "high"}}, {urgent: {$eq: true}}]}
$searchFuzzy search, case-sensitive{status: {$search: "active"}}
$search_ciFuzzy search, case-insensitive{status: {$search_ci: "active"}}
$nsearchFind records that do not contain the specified string value, case-sensitive{status: {$nsearch: "active"}}
$nsearch_ciFind records that do not contain the specified string value, case-insensitive{status: {$nsearch_ci: "active"}}
$emptyData is null{status: {$empty: true}}
$nemptyData is not null{status: {$nempty: true}}

Sorting orderBy

The orderBy` parameter is used to specify the sorting method of query results and supports multi-field sorting (up to 3 fields).

Single Field Sorting

const {
data
} = await models.post.list({
filter: {
where: {},
},
orderBy: [{
createdAt: "desc", // By creation time in descending order
}, ],
select: {
$master: true,
},
});

Multi-field Sorting

const {
data
} = await models.post.list({
filter: {
where: {},
},
orderBy: [{
featured: "desc", // First by featured status in descending order
},
{
createdAt: "desc", // then by creation time in descending order
},
{
title: "asc", // Finally by title in ascending order
},
],
select: {
$master: true,
},
});

Sorting direction:

  • "asc": Ascending order
  • "desc": Descending order

Pagination Parameters

pageSize and pageNumber

Used to implement pagination query:

const {
data
} = await models.post.list({
filter: {
where: {},
},
pageSize: 10, // 10 records per page
pageNumber: 2, // Page 2 (starting from 1)
getCount: true, // Get total count for calculating the total number of pages
select: {
$master: true,
},
});

console.log(data);
// {
// "records": [...], // 10 records on page 2
// "total": 156 // Total number of records
// }

// Calculate total pages
const totalPages = Math.ceil(data.total / 10);

getCount

Controls whether to return the total number of records that meet the criteria:

const {
data
} = await models.post.list({
filter: {
where: {
status: {
$eq: "published"
}
},
},
getCount: true, // When set to true, returns the total field
select: {
_id: true,
title: true,
},
});

console.log(data.total); // Total number of records meeting the criteria

Complete Query Sample

The following is a complete query sample containing all parameters:

const {
data
} = await models.post.list({
// Field selection
select: {
_id: true,
title: true,
excerpt: true,
createdAt: true,
updatedAt: true,
author: {
_id: true,
name: true,
avatar: true,
},
comments: {
_id: true,
content: true,
createdAt: true,
},
},

// Query conditions
filter: {
where: {
$and: [{
status: {
$eq: "published"
}
},
{
$or: [{
title: {
$search: "technology"
}
},
{
tags: {
$in: ["frontend", "backend"]
}
}
]
},
{
createdAt: {
$gte: Date.now() - 7 * 24 * 60 * 60 * 1000 // last 7 days
}
}
]
},
relateWhere: {
comments: {
where: {
status: {
$eq: "approved"
} // Query only reviewed comments
}
}
}
},

// Sort
orderBy: [{
featured: "desc"
},
{
createdAt: "desc"
}
],

// Pagination
pageSize: 20,
pageNumber: 1,
getCount: true,
});

console.log("Query result:", data.records);
console.log("Total records:", data.total);
console.log("Total pages:", Math.ceil(data.total / 20));

Join Query Details

Filter by Association

Using relateWhere allows filtering the primary model based on the conditions of associated models:

// Query articles with specific comments
const {
data
} = await models.post.list({
filter: {
relateWhere: {
// Articles must have comments
comments: {
where: {
$and: [{
content: {
$nempty: true
}
}, // Comment content is not empty
{
status: {
$eq: "approved"
}
}, // Comment reviewed
{
rating: {
$gte: 4
}
} // Comment rating >=4
]
}
},
// Articles must have tags
tags: {
where: {
name: {
$in: ["technology", "tutorial", "sharing"]
}
}
}
},
where: {
status: {
$eq: "published"
}
}
},
select: {
$master: true,
comments: {
content: true,
rating: true,
status: true,
},
tags: {
name: true,
}
}
});

Join Query Performance Optimization

  1. Precise field selection: Select only the necessary associated fields.
  2. Use association filtering appropriately: Avoid overly complex association conditions.
  3. Pagination: Use pagination for large volumes of associated data.
// Optimization example: Retrieve only necessary associated data
const {
data
} = await models.post.list({
filter: {
where: {
status: {
$eq: "published"
}
}
},
select: {
_id: true,
title: true,
excerpt: true,
// Retrieve only the author's basic information
author: {
_id: true,
name: true,
},
// Retrieve only the latest 3 comments
comments: {
_id: true,
content: true,
createdAt: true,
}
},
orderBy: [{
createdAt: "desc"
}],
pageSize: 10,
pageNumber: 1,
});

Best Practices

1. Field Selection Optimization

// ❌ Not recommended: querying all fields
const {
data
} = await models.post.list({
select: {
$master: true
},
filter: {
where: {}
}
});

// ✅ Recommended: Select only the required fields
const {
data
} = await models.post.list({
select: {
_id: true,
title: true,
excerpt: true,
createdAt: true,
},
filter: {
where: {}
}
});

2. Query Conditions Optimization

// ✅ Recommended: Use indexed fields for queries
const {
data
} = await models.post.list({
filter: {
where: {
_id: {
$eq: "specific-id"
}, // Primary key query, best performance
status: {
$eq: "published"
}, // indexed field
createdAt: {
$gte: timestamp
} // Time range query
}
}
});

// ⚠️ Caution: Fuzzy search has poor performance; use with caution.
const {
data
} = await models.post.list({
filter: {
where: {
title: {
$search: "keyword"
} // Fuzzy search; recommended to be used with other conditions
}
}
});

3. Pagination Handling

// ✅ Recommended: Reasonable page size
const pageSize = 20; // Recommended range: 10-50
const pageNumber = 1;

const {
data
} = await models.post.list({
filter: {
where: {}
},
pageSize,
pageNumber,
getCount: true, // Get total count for pagination calculation
select: {
_id: true,
title: true,
createdAt: true,
}
});

// Calculate pagination information
const totalPages = Math.ceil(data.total / pageSize);
const hasNextPage = pageNumber < totalPages;
const hasPrevPage = pageNumber > 1;

4. Error Handling

try {
const {
data
} = await models.post.list({
filter: {
where: {
status: {
$eq: "published"
}
}
},
select: {
_id: true,
title: true,
},
pageSize: 10,
pageNumber: 1,
getCount: true,
});

console.log("Query succeeded:", data);
} catch (error) {
console.error("Query failed:", error);
// Handle error cases
}

By properly using these query parameters, you can achieve efficient and flexible data query operations to meet various complex business requirements.