Сan’t create a user in the Firebase Database pls help or
tell me a documentation on this question.
Is it right stroke user_id: cred.user.uid ?
methods: {
signup(){
if(this.alias && this.email && this.password){
this.feedback = null
this.slug = slugify(this.alias, {
replacement: '-',
remove: /[$*_+~.()'"!\-:#]/g,
lower: true
})
let ref = db.collection('users').doc(this.slug)
ref.get().then(doc => {
if(doc.exists){
this.feedback = 'This alias already exists'
} else {
// this alias does not yet exists in the db
firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
.then(cred => {
ref.set({
alias: this.alias,
geolocation: null,
user_id: cred.user.uid
})
}).then(() => {
this.$router.push({ name: 'GMap' })
})
.catch(err => {
this.feedback = err.message
})
}
})
} else {
this.feedback = 'Please fill in all fields'
}
}
}
See the solution in the comments below
https://www.udemy.com/course/build-web-apps-with-vuejs-firebase/learn/lecture/10015192#questions/11358100
Related
I don't know If I'm checking for the value of the boolean correctly
what this code does: the user creates a note for himself, his ID is on the note and it needs to belong to a category name that has to be in the category schema ( where my error happens )
exports.postAddNote = (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const error = new Error("validation failed, entered data is incorrect");
throw error;
}
const content = req.body.content;
const tags = req.body.tags;
const categoryName = req.body.categoryName;
let creator;
const note = new Note({
content: content,
categoryName: categoryName, // work
tags: tags,
creator: req.userId,
});
Category.find()
.select("-_id")
.select("-__v")
.select("-notesId")
.then((categories) => {
console.log(categories); //stripping everything but names off categories
const CategoryExists = categories.some(
(category) => category.name === categoryName
);
console.log(CategoryExists); // ~~~~~~~~~~ this logs correctly
if (CategoryExists === -0) { // ~~~~~~~~~~ what i want: if the value is false
return res.json({ Error: "The category you entered does not exist" });
}
note // ~~~~~~~~~~ the code stops here :/ it doesn't save the note
.save()
.then((note) => {
console.log("saved note");
User.findById(req.userId);
})
.then((user) => {
creator = user;
user.notes.push(note);
return user.save();
})
.then((result) => {
res.status(201).json({
info: {
dateCreated: new Date().toISOString(),
status: "Note Created Successfully",
creator: { _id: creator._id, email: creator.email },
},
});
})
.catch((err) => {
if (!err.statusCode) {
err.statusCode = 500;
}
});
})
.catch((err) => {
console.log(err);
next();
});
};
if (CategoryExists === -0)
should be
if (CategoryExists === false)
or just
if (!CategoryExists)
i believe. did you try that? not sure why you are using -0. the return value for some() is either going to be true or false.
try this:
if (!CategoryExists) {
return res.json({ Error: 'The category you entered does not exist' });
}
I have some firebase queries where I am using their recommended promises but I am running to a problem. I need the code to go through the steps in order but the last snippet of code is running before the prior code finishes. I would like to use async/await but I am not sure exactly how to do it.
here is my current code:
if (result.user.emailVerified) {
let ref = db.collection('users').where('email', '==', result.user.email)
ref.get().then(snapshot => {
if (snapshot.empty) {
let cid = null
let docID = null
let groupID = null
let pendingRef = db.collection('pendingusers')
pendingRef = pendingRef.where('email', '==', result.user.email)
pendingRef.get().then(snapshot => {
if (!snapshot.empty) {
snapshot.forEach(doc => {
cid = doc.data().cid
docID = doc.id
groupID = doc.data().groupID
})
}
}).then(() => {
db.collection('users').add({
url: null,
fullPath: null,
roles: ['member'],
uid: result.user.uid,
email: result.user.email,
emailVerified: result.user.emailVerified,
cid: cid,
active: null,
joined: Date.now()
}).then(() => {
// STEP 1
console.log('1. user has been added')
if (groupID !== null) {
db.collection('groups').doc(groupID).update({
members: firebase.firestore.FieldValue.arrayUnion(result.user.uid)
}).then(() => {
// STEP 2
console.log('2. group has been updated')
})
}
}).then(() => {
if (docID !== null) {
db.collection('pendingusers').doc(docID).delete()
.then(() => {
// STEP 3
console.log('3. removed from pending ', cid)
let churchRef = db.collection('churches')
churchRef = churchRef.where('cid', '==', cid)
churchRef.get().then((querySnapshot) => {
if (!querySnapshot.empty) {
querySnapshot.forEach((doc) => {
// STEP 4
console.log('4. data ', doc.data())
dispatch('AppData/resetNotifications', [], {
root: true
})
dispatch('AppData/resetUnits', [], {
root: true
})
dispatch('AppData/isRunning', false, {
root: true
})
dispatch('AppData/setChurchId', doc.data().cid, {
root: true
})
// set the church
dispatch('AppData/allChurches', [{
churchtitle: doc.data().churchtitle,
cid: doc.data().cid,
}], {
root: true
})
})
}
})
})
}
})
})
} else {
snapshot.forEach(doc => {
commit('updateUser', {
cid: doc.data().cid,
url: doc.data().url,
fullPath: doc.data().fullPath,
user_name: doc.data().user_name
})
dispatch('AppData/getCourse', {
cid: doc.data().cid,
userid: doc.data()
}, {
root: true
})
dispatch('AppData/getActiveCourse', {
cid: doc.data().cid,
user: doc.data()
}, {
root: true
})
})
}
}).then(() => {
// STEP 5
console.log('5. next step')
dispatch('AppData/getSections', {}, {
root: true
})
dispatch('AppData/getUnits', {}, {
root: true
})
dispatch('AppData/getMissions', {}, {
root: true
})
dispatch('AppData/getWeeks', {}, {
root: true
})
// get user's current roles
let ref = db.collection('users').where('email', '==', result.user.email)
ref.onSnapshot(snapshot => {
snapshot.docChanges().forEach(change => {
let docs = change.doc
commit('setRoles', docs.data().roles)
})
})
router.push('home')
})
} else {
// console.log('not verified')
commit('setLoginFeedback', {
code: 'no-verfied email',
message: 'You must first verifiy your email.'
});
}
I have commented the steps to help illustrate the flow. I would like the code to go from step 1,2,3,4,5 but currently it goes 5,1,2,3,4
I know async/await will solve this, I just need some guidance on converting the code from then() to async/await
I created a sample registration form in my Vue App to automatically create a Firestore document with the User UID attached to it with a custom document ID.
The user gets created successfully but the document doesn't get created and doesn't display any error on the console even after using the catch() error method.
register() {
//Generate pin
function generateQuickGuid() {
return Math.random()
.toString(36)
.substring(2, 15);
}
let ref = fs.doc(generateQuickGuid());
ref.get().then(doc => {
if (doc.exists) {
console.log("Pin Exists");
} else {
console.log("pin doesnt exists");
// then add user to firestore
if (
this.email &&
this.password &&
this.displayName &&
this.category
) {
auth
.createUserWithEmailAndPassword(this.email, this.password)
.then(cred => {
ref
.set({
Name: this.displayName,
address: "close to understanding, firebase, auth",
phone: "09808763987",
category: this.category,
alias: pin,
user_id: cred.user.uid
})
.catch(e => {
console.log(e);
});
console.log("User Added");
})
.catch(error => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
console.log(errorCode, errorMessage);
});
}
}
});
}
register() {
//Generate pin
function generateQuickGuid() {
return Math.random()
.toString(36)
.substring(2, 15);
}
let ref = fs.doc(generateQuickGuid());
ref.get().then(doc => {
if (doc.exists) {
console.log("Pin Exists");
} else {
console.log("pin doesnt exists");
// then add user to firestore
if (
this.email &&
this.password &&
this.displayName &&
this.category
) {
AuthResult authResult = auth
.createUserWithEmailAndPassword(this.email, this.password)
.catch(error => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
console.log(errorCode, errorMessage);
});
ref.set({
Name: this.displayName,
address: "close to understanding, firebase, auth",
phone: "09808763987",
category: this.category,
alias: pin,
user_id: authResult.getUser().getUid()
})
.catch(e => {
console.log(e);
});
}
}
});
}
Try this
I trying to implement a favorite toggle where it saves the favorites in an array, I create a Schema and a router, the code you can see below the problem is when I try to test it on insomnia I'm getting undefined on my console.log(isFavorite). I don't know what could be wrong.
const userSchema = new Schema({
username: String,
email: String,
password: String,
favorites: [{ type: Schema.Types.ObjectId, ref: "Places" }],
},
{
timestamps: true,
});
// route
router.put("/favorites/:placeId", (req, res) => {
const userId = "5ebd13df31430045957db8c3";
User.findById(userId).then( (user) => {
const isFavorite = user.favorites.find( (favorite) => {
return favorite === req.params.placeId;
});
console.log(isFavorite);
console.log(req.params.placeId);
if (isFavorite) {
User.findOneAndUpdate(
{ _id: userId },
{
$pull: { favorites: req.params.placeId },
},
{
new: true,
})
.then((user) => res.json(user))
.catch((err) => res.status(400).json(err));
} else {
User.findOneAndUpdate(
{ _id: userId },
{
$push: { favorites: req.params.placeId },
},
{
new: true,
})
.then((user) => res.json(user))
.catch((err) => res.status(400).json(err));
}
});
});
this chunk is bad:
User.findById(userId).then((user) => {
const isFavorite = user.favorites.find((favorite) => {
return favorite === req.params.placeId;
});
instead must use populate():
let favorites = await User.findById(userId).populate('favorites');
and then filter favorites by placeId
i am having an issue, i want to update hobbies as a array (like- {"hobbies":["running","dancing"]} )
User is a model.
router.patch('/userInfo', async (req, res) => {
const updates = Object.keys(req.body);
const allowedUpdates = ['userId', 'userImages','intrestedIn', 'hobbies']`
const isValidOperation = updates.every((update) => {
return allowedUpdates.includes(update)
});
if (!isValidOperation) {
return res.send({
error: "Validation fail"
})
}
try {
const user = await User.findOne({ _id: req.body.userId }, req.body)
console.log(user)
if (!user) {
return res.send({
error: 'Invalid user Id'
})
}
updates.forEach((update) => {
user[update] = req.body[update]
})
await user.save()
return res.send({ user })
} catch (e) {
res.send(e)
}
})
and output is that, but i want array(like intrestedIn output)
{
"user": {
"intrestedIn": [
"Female"
],
"hobbies": [
"{\"hobbies\":[\"dancing\",\"running\"]} "
],
"_id": "5ec71c43026b2f1d640b657f"
}
}