Question
I’m working on a query that would **count** number of referenced item in a **Multi-Reference** field **for each item** in a collection and **update count** of referenced items in **Count of Likes** field.
Here’s a screenshot of the two fields I’m working with:
Does anyone know how to count number of referenced items and update Count of Likes field to contain number of references (or number of likes)?
My Code
I wrote this code but any item (or blog post) that has more than 50 referenced items (more than 50 likes) has `blogPost.likes.length` always returning 50 and not the actual count of likes:
import wixData from 'wix-data';
export async function updateLikesCount() {
// retrieve 50 items at a time and store them into results variable
let results = await wixData.query("BlogPosts")
.include('likes')
.find();
// place retrieved items into allBlogPosts variable
let allBlogPosts = results.items;
// check if collection has more items
while (results.hasNext()) {
// overwrite items in results variable with next set of items
results = await results.next();
// add newly retrieved items to the allBlogPosts variable
allBlogPosts = allBlogPosts.concat(results.items);
}
// recalculate and update count of likes for each blog post
const updatedBlogPosts = allBlogPosts.map(blogPost => {
const countOfLikes = blogPost.likes.length;
blogPost.countOfLikes = countOfLikes;
return blogPost;
});
// write function to bulk-update count for all blog posts here
return updatedBlogPosts;
}
What I Already Tried
Reading through documentation on [include()](https://www.wix.com/velo/reference/wix-data/wixdataquery/include) function I see that there's a limit of 50 items in a multi-reference field. That explains why `blogPost.likes.length` doesn't return a value more than 50.
I also tried using queryReferenced() function. queryReferenced()
does return accurate count of referenced items for a given blog post, but it doesn’t return a blog post data which means I can’t run the bulkUpdate() function, or update() function for that matter, because items that are passed to both bulkUpdate()
and update()
must have all properties populated in order to not lose any data from item being updated.
Goal
How can code be written to:
- Retrieve all properties of an item (of a blog post).
- Accurately count number of likes an item received in a multi-reference field.
- Update the Count Of Likes field with accurate number of likes
Any ideas?