top of page
  • Writer's pictureAndyH

Query a list or library

Updated: Mar 13, 2019


Querying a SharePoint list is not puzzling

Querying a SharePoint list or library is not a puzzle thanks to the power and flexibility of PnPJS.



In this example I want to get one or more items from a document library:

sp.web.lists.getByTitle( "MyLibrary" ) .items .select("Id, Title, Approver/Title, Approver/EMail") .filter( "Title eq 'Hello World'" ) .orderBy( "Title" ) .expand( "Approver/Id" ) .get();

The library I am interested in is "MyLibrary" and the first part of the statement is to get that. In SharePoint a library is based upon a list so it is queried through the lists property:


sp.web.lists.getByTitle( "MyLibrary" )


Next we request the .items and can now provide some specifics, all of which are optional:

  • select - use to specify the columns to return.

  • filter - use to add a filter to the results, in this case to return items that equal 'Hello World'.

  • orderBy - use to return items sorted into the order specified.

  • expand - use in conjunction with select to expand upon properties of a column that has its own properties. Read more about expand.

Finally we can ask for the items to be returned with the get() method.


How to consume the data


Following a get() to return the results, use .then( ... ) to process them:

.then( ( data: MyModel[] ) => { data.forEach( ( i ) => { items.push( { Title: i.Title, Id: i.Id, Approver: i.Approver } ); } ); } );

MyModel in this case is a class which is defined as:

export default class MyModel { public Id: number; public Title: string; public Approver: SPPersonModel; }

Approver is a Person or Group column which has its own properties. This has been defined in the SPPersonModel as follows:

export class SPPersonModel { public Title: string; public Id: number; public Name: string; public FirstName: string; public LastName: string; public Account: string; public EMail: string; public SipAddress: string; }

I have a feeling there might be an easier way to work with the data returned but defining and populating the classes is quite familiar to me so this will do for today.


What about the REST?


PnPJS hides the REST API from us but I've found that it is still useful to understand it. In particular it has been handy to take a closer look at the data returned from REST. All the browsers have some useful extensions to make working with REST easier too.


Documentation


Find out more about getting list item data from PnPJS's Packages documentation.


171 views0 comments

Recent Posts

See All
bottom of page