Getting List of Database IDs from Notion API
I need help getting all database IDs that my integration can access through the Notion API. Ideally, I would like a response that looks like this:
{
object: 'list',
results: [
{
object: 'block',
id: 'b92g7037-8e3c-54dd-854e-gd3578b716c5',
created_time: '2022-02-12T18:18:00.000Z',
last_edited_time: '2022-02-15T16:29:00.000Z',
has_children: false,
archived: false,
type: 'child_database',
child_database: { title: 'Records' }
}
],
next_cursor: null,
has_more: false
}
In reality, I only need the IDs and titles of the databases. Everything was working perfectly until users started reorganizing content, which led to databases being nested within other blocks.
I’ve attempted using the search API with certain filters, but the output is overwhelming, with unnecessary data such as parent pages and individual database rows:
const fetchAllDatabases = async () => {
console.log('Fetching databases...');
const dbResults = await notion.search({
filter: {
value: 'database',
property: 'object'
}
});
console.log('Results:');
console.dir(dbResults, { depth: null });
}
The results provide excessive information, including all properties and rows of the databases. My objective is simply to create an array like this: [database_id_1, database_id_2].
Additionally, I tried to recursively check through the page blocks:
const fetchBlockChildren = async (pageId) => {
const blockList = await notion.blocks.children.list({
block_id: pageId
});
return blockList;
}
const extractDatabases = async (pageId) => {
let dbIds = [];
const blockList = await fetchBlockChildren(pageId);
blockList.results.forEach( async (block) => {
if (block.has_children === true) {
const nestedDatabases = await extractDatabases(block.id);
dbIds = [...dbIds, ...nestedDatabases];
}
if (['child_database', 'database'].includes(block.type)) {
dbIds.push(block.id)
}
});
return dbIds;
}
However, I encountered challenges with async/await when using forEach loops. I attempted to implement Promise.all with map/filter, but ran into problems with mismatched array sizes during recursion.
What would be the best method to obtain a concise list of all database IDs accessible to my app?