I'm working on a Node.js project using Firebase Realtime Database, and I'm encountering an error when trying to match clients with therapists based on their responses. The error message I receive is "db._checkNotDeleted is not a function".
Here's the relevant part of my match.js file where the error occurs:
// utils/match.js
const { getDatabase, ref, get, query, orderByChild, equalTo } = require('firebase/database');
const { firebaseApp } = require('./firebaseConfig');
// Function to calculate the score based on responses
const calculateMatchScore = (clientResponses, therapistResponses) => {
let score = 0;
// Score for language compatibility
const sharedLanguages = clientResponses.languages.filter(language =>
therapistResponses.languages.includes(language)
);
score += sharedLanguages.length * 10; // Assign 10 points for each shared language
// Score for communication preferences
const sharedCommunicationMethods = clientResponses.communication.filter(method =>
therapistResponses.communication.includes(method)
);
score += sharedCommunicationMethods.length * 5; // Assign 5 points for each shared communication method
// Score for therapy experiences
const matchingTherapyExperiences = clientResponses.therapy_experiences.filter(experience =>
therapistResponses.therapy_experiences.includes(experience)
);
score += matchingTherapyExperiences.length * 15; // Assign 15 points for each matching therapy experience
return score;
};
// Function to match clients with therapists
const matchClientsWithTherapists = async () => {
const db = getDatabase(firebaseApp);
const usersRef = ref(db, 'users');
const responsesRef = ref(db, 'responses');
const matchesRef = ref(db, 'matches');
// Retrieve all therapists and clients
const therapistsSnapshot = await get(query(usersRef, orderByChild('role'), equalTo('therapist')));
const clientsSnapshot = await get(query(usersRef, orderByChild('role'), equalTo('client')));
if (!therapistsSnapshot.exists() || !clientsSnapshot.exists()) {
throw new Error('No therapists or clients found');
}
const therapists = therapistsSnapshot.val();
const clients = clientsSnapshot.val();
// Create an array to store potential matches
let potentialMatches = [];
// Calculate scores for each client-therapist pair
for (const clientId in clients) {
const clientResponsesSnapshot = await get(ref(responsesRef, clientId));
const clientResponses = clientResponsesSnapshot.val();
for (const therapistId in therapists) {
const therapistResponsesSnapshot = await get(ref(responsesRef, therapistId));
const therapistResponses = therapistResponsesSnapshot.val();
const score = calculateMatchScore(clientResponses, therapistResponses);
potentialMatches.push({ clientId, therapistId, score });
}
}
// Sort potential matches by score
potentialMatches.sort((a, b) => b.score - a.score);
// Distribute clients to therapists, ensuring no therapist has more than 5 clients
// and that clients are evenly distributed
const matches = {};
potentialMatches.forEach(match => {
if (!matches[match.therapistId]) {
matches[match.therapistId] = [];
}
if (matches[match.therapistId].length < 5) {
matches[match.therapistId].push(match.clientId);
}
});
// Save the matches to the database
for (const therapistId in matches) {
const therapistMatchesRef = push(ref(matchesRef, therapistId));
await set(therapistMatchesRef, matches[therapistId]);
}
return matches;
};
module.exports = { matchClientsWithTherapists };
And here's my firebaseConfig.js:
//utils/firebaseConfig.js
require('dotenv').config();
const { initializeApp } = require("firebase/app");
const { getDatabase, ref, set, get } = require("firebase/database");
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID
};
const firebaseApp = initializeApp(firebaseConfig);
module.exports = {firebaseApp}
and then i use the function like this
// routes/router.js
const express = require('express');
const router = express.Router();
const { matchClientsWithTherapists } = require('../utils/match');
//other routes
// Route to trigger the matching process
router.post('/api/match', async (req, res) => {
try {
const matches = await matchClientsWithTherapists();
res.status(200).json({ success: true, matches });
} catch (error) {
console.error('Error during matching process:', error);
res.status(500).json({ message: error.message });
}
});
I've confirmed that my .env file is correctly set up with all the necessary Firebase configuration variables. I've also made sure that require('dotenv').config(); is called at the beginning of my application's entry point.
I'm using Firebase SDK version 10.7.2 and Node.js version 18.17.0
I've tried reinstalling node modules, checking Firebase imports, and ensuring there are no network issues. I've also checked the Firebase Console for any configuration issues.
Can anyone help me understand why this error is occurring and how to fix it?
Thank you in advance!
i used the same firebaseConfig in another function and it works
//utils/register.js
const { hashPassword } = require('./hash');
const crypto = require('crypto');
const { getDatabase, ref, set, get, push,equalTo,orderByChild,query } = require('firebase/database');
const { firebaseApp } = require('./firebaseConfig');
const sendRegistrationEmail = require('./sendRegistrationEmail');
const registerUser = async (firstName, lastName,email,phoneNumber,username,password,role,responses) => {
const db = getDatabase(firebaseApp);
// Query the database for a user with the specified email
const usersRef = ref(db, 'users');
const emailQuery = query(usersRef, orderByChild('email'), equalTo(email));
const emailSnapshot = await get(emailQuery);
// Check if the email already exists
if (emailSnapshot.exists()) {
throw new Error('Email already in use');
}
// Check if the username already exists
const usernameRef = ref(db, `usernames/${username}`);
const usernameSnapshot = await get(usernameRef);
if (usernameSnapshot.exists()) {
throw new Error('Username already taken');
}
try {
const hashedPassword = await hashPassword(password);
// Generate a new unique userId
const newUserRef = push(ref(db, 'users'));
const userId = newUserRef.key;
//Generate a verification token for the new user
const verificationToken = crypto.randomBytes(20).toString('hex');
// Save user details to the database
const userData = {
userId,
username,
email,
phoneNumber,
role,
password: hashedPassword,
firstName,
lastName,
isVerified:false,
verificationToken,
};
await set(newUserRef, userData);
// Also, save the username to prevent duplicates
await set(usernameRef, { userId });
// Save responses to a separate document (table) referenced by userId
if (responses) {
const responsesRef = ref(db, `responses/${userId}`);
await set(responsesRef, responses);
}
await sendRegistrationEmail(email, firstName, verificationToken);
return { success: true, message: 'User registered successfully', userId };
} catch (error) {
console.log(`Error while trying to create a new user: ${error.message}`);
console.error('Error registering user:', error);
throw error;
}
};
module.exports = { registerUser };
however in the matching function i get
Error during matching process: TypeError: db._checkNotDeleted is not a function
at ref (C:\Users\USER\Documents\GitHub\backend\node_modules\@firebase\database\dist\index.node.cjs.js:12964:8)
at matchClientsWithTherapists (C:\Users\USER\Documents\GitHub\backend\utils\match.js:55:47)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async C:\Users\USER\Documents\GitHub\backend\routes\router.js:141:21