SharePoint REST APIs does not allow to Managed Metadata / Taxonomy fields within the OData $filter parameter. So, PnPjs which uses REST APIs internally, cannot query on a Managed Metadata column using the .filter() method.
But we can query using CAML query and the .getItemsByCAMLQuery method. Below is a sample document library which is has some policy documents uploaded and there is Managed Metadata Field called 'Deparments' which accepts multiple values.
Below is a sample PnPjs V2 snippet which finds the list of documents that are tagged with a specific Managed Metadata term.
import { setup as pnpSetup } from "@pnp/common"; import { sp } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/lists/web"; import "@pnp/sp/items/list";... protected onInit(): Promise<void> { return super.onInit().then(_ => { pnpSetup({spfxContext: this.context}); }); } ...
const queryView =
<View> <Query> <Where><Eq> <FieldRef Name="Department" /> <Value Type='TaxonomyFieldTypeMulti'>HR</Value> </Eq></Where> </Query> </View>
;const docs = await sp.web.lists .getByTitle("Policies") .getItemsByCAMLQuery({ViewXml: queryView},"File"); docs.map(doc => { const depts = doc.Department.map(dept => {return dept.Label}); console.log(`Url : ${doc.File.ServerRelativeUrl} || Department : ${depts.join(",")}`); });
This will filter for all the documents which are tagged with the Taxonomy term 'HR'. And here is the output showing the required documents that are filtered.
This can be used in scenarios where an SPFx webpart should show content based on the current user's properties. The above example can be extended to show policy documents for the current user's department. The user's department can be fetched from the profile and the value can be passed to the CAML Query.