Version: next

Queries

The DataStore Models provides two functions for executing queries.

query()

Here we can fetch all documents for a Model or a selection of the documents using filters.

TaskModel.query().then((data) => {}) // Retrieves all tasks

In the code snippet above, we fetch all tasks. To fetch a selection of the documents we can use filters. We filter using expressions and operators.

Operators

All supported operators:

OperatorValue
neInput not equal to value
eqInput equal to value
leInput less than or equal to value
ltInput less than (strict) value
geInput greater than or equal to value
gtInput greater than (strict) value
inInput array or string contained in value
containsValue starts with input
startsWithValue starts with input
endsWithValue ends with input

Operator support:

OperatorMathematicalStringDateArrayBoolean
ne✔️✔️✔️✔️✔️
eq✔️✔️✔️✔️✔️
le✔️✔️✔️✖️✖️
lt✔️✔️✔️✖️✖️
ge✔️✔️✔️✖️✖️
gt✔️✔️✔️✖️✖️
in✔️✔️✔️✔️✔️
contains✖️✔️✖️✔️✖️
startsWith✖️✔️✖️✔️✖️
endsWith✖️✔️✖️✔️✖️

Examples:

TaskModel.query({ title: "test" }); // Fetch all tasks where title = 'test'
TaskModel.query({
title: { ne: 'test' }
}); // Fetch all tasks where title != 'test'
TaskModel.query({
numberOfDaysLeft: {
ge: 5, lt: 20
}
}); // Fetch all tasks where numberOfDaysLeft >= 5 and < 20
TaskModel.query({
title: 'test',
numberOfDaysLeft: { gt: 5 }
}); // Fetch all tasks where title = 'test' and numberOfDaysLeft > 5

You can also create expressions with the following logical operators:

  • AND
  • OR
  • NOT
TaskModel.query({
or: {
title: "test",
not: { numberOfDaysLeft: { gt: 5 } }
}
}); // Fetch all tasks where (title = 'test') or (numberOfDaysLeft is not > 5)

queryById()

Here we fetch documents using their primary key. Quering by Id is faster because DataStore index documents by their primary key.

const task = await TaskModel.queryById(documentId);