Hi, im making a custom registration page and have followed the turorials for this and collecting email, phone number and all the other information to a data collection just fine. But when I want to make each user get their own number based on the the number of previous users i ran into a problem.
The idea is to give each user registrated a customer number based how many users that is allready registrated. So: let customerNumber = currentAmountOfUsers + 1
I display the “customerNumber” data (se code) on a profile page but it only shows " [object Object] ".
Im pretty new to JavaScript but I thought the “getData()” function would return a number because of the " results.items.length ".
Please help a newbie out !
My code:
function getData() {
let query = wixData.query("Members");
return query.limit(1000).find().then(results => {
console.log('getData', results);
return results.items.length;
});
}
export function loginButton_click(event) {
//Add your code for this event here:
// user is logged in
if (wixUsers.currentUser.loggedIn) {
// log the user out
wixUsers.logout()
.then(() => {
// update buttons accordingly
$w("#loginButton").label = "Login";
$w("#profileButton").hide();
});
}
// user is logged out
else {
let userId;
let userEmail;
// prompt the user to log in
wixUsers.promptLogin({ "mode": "login" })
.then((user) => {
userId = user.id;
return user.getEmail();
})
.then((email) => {
// check if there is an item for the user in the collection
userEmail = email;
return wixData.query("Members")
.eq("_id", userId)
.find();
})
.then((results) => {
// if an item for the user is not found
if (results.items.length === 0) {
// create an item
const toInsert = {
"_id": userId,
"email": userEmail,
"customerNumber":getData()
};
// add the item to the collection
wixData.insert("Members", toInsert)
.catch((err) => {
console.log(err);
});
}
// update buttons accordingly
$w("#loginButton").label = "Logout";
$w("#profileButton").show();
wixLocation.to(`/members-1/update/${wixUsers.currentUser.id}`);
})
.catch((err) => {
console.log(err);
});
}
}
Apart for some other things, you make a conceptual error: there is a difference between:
a) the total amount of rows that comply with a query (query.count)
b) the limited amount from a) that is returned to the front end (array.length)
For a, look at https://www.wix.com/corvid/reference/wix-data.WixDataQuery.html#count . count gives you the real total that you are looking for. But …: since you limit the amount of rows returned to the frontend to 1000 (=.lenght of the array returned), this will only work for 1000 entries, then it will go wrong, because every time the next one will be 1001. So will end up with a lot of 1001´s.
In short, change code to check for query.count, not for array.length.
Hi Giri Zano! Thanks for the answer, now the console logs a number and im one step closer.
but it still saves “customerNumber” as an object and gets displayed as " [object Object] ".
function getData() {
let query = wixData.query("Members");
return query.count().then(num => {
console.log('getData', num);
return num;
});
}
I want to save “num” in the database as an string or number
// create an item
const toInsert = {
"_id": userId,
"email": userEmail,
"customerNumber":getData()
};
// add the item to the collection
wixData.insert("Members", toInsert)
.catch((err) => {
console.log(err);
});
What am I doing wrong here? Do I have to do something to “getData” so it becomes a string?
I kept trying to define the returned data in an variable, but what i get in the database is an " [object Promise] ". How do i get it to be a number?
OK, small steps at a time. First, that “return num” doesn´t do anything, the return above it has precedence. But, it doesn´t matter. You must understand that you are returning the result of a query. A query returns an object. And your num is hidden somewhere inside that object and you must offer the correct “path” to it.
To help you understand this, try this (assuming it´s all in same file, if not, put “export” in front of async and “import” it;
async function getData() {
let query = await wixData.query("Members");
return query
});
}
and then, the calling function, try a JSON.stringify (look up what that means here JSON.stringify() ) like so:
// create an item
// assuming this part is also declared as “async”, otherwise the await will have a red dot in front of it
let objData = await getData();
console.log("Returned from query : " + JSON.stringify(objData));
//for you to find out: how to retrieve the number from objData
const toInsert = {
"_id": userId,
"email": userEmail,
"customerNumber": theNumberYouFoundOut
};
// add the item to the collection
wixData.insert("Members", toInsert)
.catch((err) => {
console.log(err);
});
PS I didn´t test this code, but it should more or less work. Have fun, this is how we learn: try, try, try, learn.
PPS Looking at your code again, and there is something strange in there. You do a “_id”: userId", meaning you constantly insert a row into a collection with the same _id, the one thing that has to be unique!!! This must go wrong the second time.
Thank you! This worked perfectly! So happy, saved me so much frustration.
This is how I wrote the function
async function getData() {
let query = await wixData.query("Members");
return query.count().then(num => {
console.log('getData', num);
return num;
});
}
This is how i fetched the number
.then(async (results) => {
// if an item for the user is not found
if (results.items.length === 0) {
let objData = await getData();
let fetchedUserNr = parseInt(JSON.stringify(objData), 10)
// create an item
const toInsert = {
"_id": userId,
"email": userEmail,
"customerNumber": fetchedUserNr + 1
};
// add the item to the collection
wixData.insert("Members", toInsert)
.catch((err) => {
console.log(err);
});
}
// update buttons accordingly
$w("#loginButton").label = "Logout";
$w("#profileButton").show();
wixLocation.to(`/members-1/update/${wixUsers.currentUser.id}`);
}
PS the id seems to be different in each row in the database so think it works fine.
Have a good day!