Skip to main content

Query Parameter Details

Cloud Development Data model provides powerful query capabilities, supporting complex query conditions, field selection, sorting order, pagination, and join queries. This document introduces various parameters and methods of use for data model query operations in detail.

Query Parameter Overview

Data model query operations mainly include the following parameters:

ParameterTypeDescriptionRequired
envTypepre | prodSpecifies the data environment for query. If not provided, it defaults to official data.
pre: experience data, prod: official data
No
selectSelectParamsSpecify returned fieldsNo
filterFilterParamsQuery filter criteriaNo
orderByOrderByParams[]Sorting criteriaNo
pageSizenumberPage size, maximum 200No
pageNumbernumberPage numberNo
getCountbooleanWhether to return the total number of returnsNo

Specify data environment envType

The envType parameter is used to specify the data environment for querying, with a default value of official data. pre: experience data, prod: official data.

const {
data
} = await models.post.list({
envType: 'pre',
filter: {
where: {},
},
select: {
$master: true,
},
});

Field selection select

The select parameter is used to specify the field that should include in the query result, supporting precise control of the model field and associated model field.

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

Return all primary model fields

Use $master: true to go back to 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 specified field named 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 associated model fields simultaneously:

const {
data
} = await models.post.list({
select: {
_id: true,
title: true,
updatedAt: true,
//Join query 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 filtering filter

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

Basic query where

Basic query filters the model field:

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

Join query relateWhere

Join query used for filtering based on associated model conditions:

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

Combination-based query example

When requiring the use of and/or relationship, you can use the $and and $or operators in the where parameter.

If $and and $or operators are used, they must be placed in an array:

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

Query operator

OperatorDescriptionExample
$eqequal{status: {$eq: "active"}}
$nenot equal to{status: {$ne: "deleted"}}
$gtmore than{score: {$gt: 80}}
$gteequal to or greater than{age: {$gte: 18}}
$ltless than{price: {$lt: 100}}
$lteless than or equal to{discount: {$lte: 0.5}}
$inin the array{category: {$in: ["tech", "news"]}}
$ninnot in the array{status: {$nin: ["deleted", "banned"]}}
$andlogical AND{$and: [{age: {$gte: 18}}, {status: {$eq: "active"}}]}
$orlogical OR{$or: [{priority: {$eq: "high"}}, {urgent: {$eq: true}}]}
$searchfuzzy query, case-sensitive{status: {$search: "active"}}
$search_cifuzzy query, case-insensitive{status: {$search_ci: "active"}}
$nsearchSearch for records excluding the specified string value, case-sensitive{status: {$nsearch: "active"}}
$nsearch_ciSearch for records excluding 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

orderBy parameter is used for specified query sorting method and supports multi-field sorting (up to 3 fields).

Single field sorting

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

Multi-field sorting

const {
data
} = await models.post.list({
filter: {
where: {},
},
orderBy: [{
featured: "desc", // Sort by featured status in reverse order first
},
{
createdAt: "desc", // Then sort by creation time in reverse chronological order
},
{
title: "asc", // sort by title in ascending order at last
},
],
select: {
$master: true,
},
});

Sorting order:

  • "asc": ascending order
  • "desc": descending order

Pagination parameters

pageSize and pageNumber

is used to implement paging 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 to calculate total number of pages
select: {
$master: true,
},
});

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

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

getCount

Control 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, // Return total field when set to true
select: {
_id: true,
title: true,
},
});

console.log(data.total); // Total record count that meet the criteria

Complete Query Example

The following is a complete query example with 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 condition
filter: {
where: {
$and: [{
status: {
$eq: "published"
}
},
{
$or: [{
title: {
$search: "technology"
}
},
{
tags: {
$in: ["frontend", "backend"]
}
}
]
},
{
createdAt: {
$gte: Date.now() - 7 * 24 * 60 * 60 * 1000 // recent 7 days
}
}
]
},
relateWhere: {
comments: {
where: {
status: {
$eq: "approved"
} // Only query reviewed comments
}
}
}
},

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

page
pageSize: 20,
pageNumber: 1,
getCount: true,
});

console.log("query result:", data.records);
console.log("total record count:", data.total);
console.log("total number of pages:", Math.ceil(data.total / 20));

Join Query Explanation

Filter by Association

Use relateWhere to filter the main model based on conditions of the associated model.

// 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 not empty
{
status: {
$eq: "approved"
}
}, // Comment reviewed
{
rating: {
$gte: 4
}
} // Comment score >= 4
]
}
},
Culture and entertainment 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 select field: Select only required associated fields.
  2. Reasonable use of association filtering: Avoid too complex association conditions.
  3. Paginate: Use pagination for large number of associated data.
// Optimization example: Only get necessary associated data
const {
data
} = await models.post.list({
filter: {
where: {
status: {
$eq: "published"
}
}
},
select: {
_id: true,
title: true,
excerpt: true,
// Only get the author's basic info
author: {
_id: true,
name: true,
},
// Only get 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: Query all fields
const {
data
} = await models.post.list({
select: {
$master: true
},
filter: {
where: {}
}
});

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

2. Query condition optimization

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

// ⚠️ Note: Fuzzy query has poor performance. Use it with caution.
const {
data
} = await models.post.list({
filter: {
where: {
title: {
$search: "keyword"
} // Fuzzy query. Recommended to use with other conditions.
}
}
});

3. Pagination Handling

// ✅ Recommended: reasonable page size
const pageSize = 20; // recommended between 10 and 50
const pageNumber = 1;

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

// Compute 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
}

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