Database Reference
In-Depth Information
function passed to its constructor. In this case, we're using the
list
function to cre-
ate an empty list when the given
parent
isn't found.
Once we have this subgraph, we can update the nodes as follows:
def
def
update_node_and_descendants
(
nodes_by_parent
,
node
,
parent
):
# Update node's ancestors
node
[
'ancestors'
]
=
parent
.
ancestors
+
[
{
'_id'
:
parent
[
'_id'
],
'slug'
:
parent
[
'slug'
],
'name'
:
parent
[
'name'
]} ]
db
.
categories
.
update
(
{
'_id'
:
node
[
'_id'
]},
{
'$set'
: {
'ancestors'
:
ancestors
,
'parent'
:
parent
[
'_id'
] } })
# Recursively call children of 'node'
for
for
child
iin
nodes_by_parent
[
node
[
'_id'
]]:
update_node_and_descendants
(
nodes_by_parent
,
child
,
node
)
In order to ensure that the subgraph-building operation is fast, we'll need an index on the
an-
cestors._id
field:
>>>
>>>
db
.
categories
.
ensure_index
(
'ancestors._id'
)
Rename a category
One final operation we'll explore with our category hierarchy is renaming a category. In order
to a rename a category, we'll need to both update the category itself and also update all its
descendants. Consider renaming “Bop” to “BeBop,” as in
Figure 5-4
.