Odd Collection Not Found Error (WDE0025)

Question:
When I load my site page, I get a strange error about 70% of the time stating ["WDE0025: The RegistrationCartItems collection does not exist. You cannot work with a collection using the Data API before it is created in the Editor."]
I understand what this would mean normally, but I do have a RegistrationCartItems collection and it pulls from it perfectly fine about 30% of the time.

Product:
Wix Editor / Velo

What are you trying to achieve:
Have the page load without errors.

What have you already tried:
My code that seems to be causing the issue is below. The error seems to occur when getCartDetails calls await getMemberCartItems().

import { Permissions, webMethod } from "wix-web-module";
import { currentMember } from 'wix-members-backend'
import wixData from 'wix-data';
import wixPayBackend from 'wix-pay-backend';

const REGISTRATION_FEE = parseFloat(100)

const sleep = ms => new Promise(r => setTimeout(r, ms));

/**
 * Retrieves current member details.
 * @returns {Promise<Object>} The details of the current member.
 */
const getCurrentMemberDetails = async () => {
    return await currentMember.getMember({ fieldsets: ["FULL"] });
}

/**
 * Retrieves cart items for a specified member.
 * @param {string} memberId - The ID of the member.
 * @param {boolean} consistentRead - Specifies if the read should be consistent.
 * @returns {Promise<Array>} An array of cart items.
 */
const getMemberCartItems = async (memberId, consistentRead) => {
    await sleep(500)
    const cartResponse = await wixData.query('RegistrationCartItems')
        .eq('contact', memberId)
        .find({ suppressAuth: true, consistentRead: consistentRead });
    return cartResponse.items;
}

/**
 * Retrieves applied coupons for a specified member.
 * @param {string} memberId - The ID of the member.
 * @param {boolean} consistentRead - Specifies if the read should be consistent.
 * @returns {Promise<Array>} An array of applied coupons.
 */
const getAppliedCoupons = async (memberId, consistentRead) => {
    const couponsResponse = await wixData.query('RCAplCpnCodes')
        .eq('contact', memberId)
        .find({ suppressAuth: true, consistentRead: consistentRead });
    return couponsResponse.items.length > 0 ? couponsResponse.items : [];
}

/**
 * Retrieves details of applied coupons.
 * @param {Array} appliedCoupons - An array of applied coupons.
 * @param {boolean} consistentRead - Specifies if the read should be consistent.
 * @returns {Promise<Array>} An array of applied coupon details.
 */
const getAppliedCouponDetails = async (appliedCoupons, consistentRead) => {
    const appliedCouponDetails = [];
    for (const appliedCoupon of appliedCoupons) {
        try {
            const result = await wixData
                .query('RegistrationCartCouponCodes')
                .eq('_id', appliedCoupon.coupon)
                .include('applicableCourses')
                .find({ suppressAuth: true, consistentRead: consistentRead });
            appliedCouponDetails.push(result.items[0]);
        } catch (error) {
            console.error(`Error processing applied coupon ${appliedCoupon._id}:`, error);
        }
    }
    return appliedCouponDetails;
}

/**
 * Adjusts cart items with coupons, showing both original and adjusted prices, 
 * and calculates the total amount off from coupons.
 * @param {Array} cartItems - An array of cart items.
 * @param {Array} appliedCouponDetails - An array of applied coupon details.
 * @returns {Object} An object containing adjusted cart items and total amount off from coupons.
 */
const adjustCartItemsWithCoupons = (cartItems, appliedCouponDetails) => {
    let totalAmountOffFromCoupons = 0;

    const adjustedCartItems = cartItems.map(item => {
        let originalPrice = item.price;
        let newPrice = originalPrice;

        const applicableCouponsToItem = appliedCouponDetails.filter(couponDetails => {
            const applicableCourseIds = couponDetails.applicableCourses.map(course => course._id);
            return applicableCourseIds.includes(item.course);
        });

        for (const coupon of applicableCouponsToItem) {
            let discountAmount = 0;
            if (coupon.percentOff > 0 && coupon.percentOff <= 100) {
                discountAmount = originalPrice * (coupon.percentOff / 100);
                newPrice -= discountAmount;
            } else if (coupon.amountOff > 0) {
                discountAmount = (coupon.amountOff > newPrice ? newPrice : coupon.amountOff);
                newPrice -= discountAmount;
            }
            totalAmountOffFromCoupons += discountAmount;
        }

        return {
            ...item,
            originalPrice: originalPrice,
            price: parseFloat(newPrice.toFixed(2))
        };
    });

    return { adjustedCartItems, totalAmountOffFromCoupons };
}

/**
 * Retrieves and adjusts current member cart items with coupon applications.
 * @returns {Promise<Object>} An object containing adjusted cart items and total amount off from coupons.
 */
const getAdjustedCartItemsForCurrentMember = async (consistentRead = true) => {
    const member = await getCurrentMemberDetails();
    const memberId = member._id;
    await sleep(100)
    const cartItems = await getMemberCartItems(memberId, consistentRead);
    await sleep(100)
    const appliedCoupons = await getAppliedCoupons(memberId, consistentRead);
    const appliedCouponDetails = await getAppliedCouponDetails(appliedCoupons, consistentRead);
    return adjustCartItemsWithCoupons(cartItems, appliedCouponDetails).adjustedCartItems;
}

export const getCartDetails = webMethod(Permissions.SiteMember, async () => {
    return await getAdjustedCartItemsForCurrentMember()
})

Additional information:
The error is only visible on site logs, in my console it only shows the following:

createConsoleProxy.ts:47 Error: Unable to handle the request. Contact the site administrator or view site monitoring logs for more information.

I have tried creating a new CMS table and using its name instead. That solved the issue for about 30 minutes then it started happening again ~70% of the time. Any help is greatly appreciated.

@anthony would you happen to have any thoughts on this one?

Already considered to put some logs into your own code?
You are not using -->LOGS<–

The more logs you will use → the more detailed you will understand what’S going on.

And this one →
const sleep = ms => new Promise(r => setTimeout(r, ms));
→ i don’t like it.

Without have taken a look onto your whole code → your setTimeOut ← is already suspecious.

Why do you need it?
await sleep(500)

and again …
await sleep(100)

Every timeOut is a risc to get errors.

It is alredy an ASYNS-Function…

const getMemberCartItems = async (memberId, consistentRead) => {
    await sleep(500)
    const cartResponse = await wixData.query('RegistrationCartItems')
        .eq('contact', memberId)
        .find({ suppressAuth: true, consistentRead: consistentRead });
    return cartResponse.items;
}

And when you think you know exactly the code-line where the error starts to be thrown on to your screen…

My code that seems to be causing the issue is below. The error seems to occur when getCartDetails calls await getMemberCartItems() .

…which is telling you the following…

createConsoleProxy.ts:47 Error: Unable to handle the request. Contact the site administrator or view site monitoring logs for more information.

…why not start to put more logs exactly at this code-region?

However, your CODING-STYLE takes getting used to.

If it would be me → i would recode your whole code using normal styled functions… like…

async function zzz(value, value, value) {
    //calling the next function...in this case an async one...
    let yyy = await yyy(value, value); console.log('yyy: ', yyy);    
}

Instead of doing that b…s… and using all these unneccessary TIME-OUTS.

const getAdjustedCartItemsForCurrentMember = async (consistentRead = true) => {
    const member = await getCurrentMemberDetails();
    const memberId = member._id;
    await sleep(100)
    const cartItems = await getMemberCartItems(memberId, consistentRead);
    await sleep(100)
    const appliedCoupons = await getAppliedCoupons(memberId, consistentRead);
    const appliedCouponDetails = await getAppliedCouponDetails(appliedCoupons, consistentRead);
    return adjustCartItemsWithCoupons(cartItems, appliedCouponDetails).adjustedCartItems;
}

@CODE-NINJA thanks for the help. I tried taking out all of the sleeps. I just had those in there in case I was hitting some form of rate limit. Here’s the code without it. I also put in console logs after each function, but it doesn’t get past the first one.

import { Permissions, webMethod } from "wix-web-module";
import { currentMember } from 'wix-members-backend'
import wixData from 'wix-data';
import wixPayBackend from 'wix-pay-backend';

// ... rest of code above...

/**
 * Retrieves and adjusts current member cart items with coupon applications.
 * @returns {Promise<Object>} An object containing adjusted cart items and total amount off from coupons.
 */
const getAdjustedCartItemsForCurrentMember = async (consistentRead = true) => {
    const member = await getCurrentMemberDetails();
    const memberId = member._id;
    console.log('currentMember is: ', memberId)
    const cartItems = await getMemberCartItems(memberId, consistentRead);
    // This is where the console error is. The rest of the function doesn't run.
    console.log('cartItems is: ', cartItems)
    const appliedCoupons = await getAppliedCoupons(memberId, consistentRead);
    const appliedCouponDetails = await getAppliedCouponDetails(appliedCoupons, consistentRead);
    return adjustCartItemsWithCoupons(cartItems, appliedCouponDetails).adjustedCartItems;
}

export const getCartDetails = webMethod(Permissions.SiteMember, async () => {
    return await getAdjustedCartItemsForCurrentMember()
})
async function getAdjustedCartItemsForCurrentMember(consistentRead = true) {
    //---STEP-I
    const member = await getCurrentMemberDetails(); 
    console.log('Member-Details: ', member);  
    //---STEP-II
    const memberId = member._id; console.log('currentMember is: ', memberId);
    //---STEP-III  
    const cartItems = await getMemberCartItems(memberId, consistentRead);    
    console.log('cartItems is: ', cartItems);
    //---STEP-IV
    const appliedCoupons = await getAppliedCoupons(memberId, consistentRead);
    console.log('Applied-Coupons: ',  appliedCoupons );
    //---STEP-V
    const appliedCouponDetails = await getAppliedCouponDetails(appliedCoupons, consistentRead);
    console.log('Applied-CouponsDetails: ',  appliedCouponDetails );
    
    return adjustCartItemsWithCoupons(cartItems, appliedCouponDetails).adjustedCartItems;
}

export const getCartDetails = webMethod(Permissions.SiteMember, async function() {
    return await getAdjustedCartItemsForCurrentMember()
});

Since it is an async-function → async function getAdjustedCartItemsForCurrentMember, it will break at a certain point (STEP). Grab the STEP which is breaking your code and investigate it in detail.

-Which data could be missing?
-Which results you get back?
-What tells you the corresponding Velo-API-DOC about the API you are using?
-Take a closer look onto CONSOLE.

These are the steps, which should give you an answer to your problem.

You seem to be an already advanced coder, normaly you should be able to solve this problem on your own, if all this CODE is not just COPY and PASTE.

While I appreciate your response, none of that is directly helpful to me. I don’t believe it’s an issue with my code functions because it runs correctly 100% of the time in Wix Editor’s Preview. It also runs correctly ~30% of the time on the published site.

I have looked in depth at the code and where it is breaking, and it’s every time it makes a wixData.query() call. It fails on random ones of them. My console logs don’t help because it’s just the generic info from the console (Error: Unable to handle the request. Contact the site administrator or view site monitoring logs for more information.).

Is there anyone else who might be able to help with information other than just the generic troubleshooting info from the docs? I’ve already identified that it’s failing on the wixData.query() calls giving a WDE0025 error.

On which page i can see all the OUTPUT-LOGS ?
Where i can recreate an ERROR?

I’m able to reproduce this issue @Luke_E will share with the relevant team: https://anthonyl5.wixstudio.io/my-site-216

Edit: Hrmm. Had a bug in my code. Need to investigate further

Question. Was the site published after the missing collection was created? Could you try publishing again and see if that’s the cause?

I tried re-publishing multiple times. I even created a new collection and changed all the references to that and then re-published. The issue persisted.

Interestingly, it works 100% of the time in preview, just not in production.

Also, tried connecting an external database, and there I got the same error (but less frequently) or a WDE0131 “This external database collection ___ does not exist.”. This error could occur in preview or production.

Thanks for clarifying. Seems like you’re now in contact with our support team so they’ll be the best way to get a resolution.