my put method duplicate the code insteade of updating - javascript

i am trying to store user data in mongodb using put method .my intension is to update those data if there exist or create new. but my method create new data insteade of updating..
this code is from client side(here first i uploaded my image to the imgbb then i save it to server).. .
const image = data.image[0];
const formData = new FormData();
formData.append('image',image)
const API_KEY = '4957c3c668ded462db1fb1002c4535e6';
const url = `https://api.imgbb.com/1/upload?key=${API_KEY}`;
fetch(url,{
method : 'POST',
body : formData,
})
.then(res => res.json())
.then(result => {
if(result.success){
console.log('image',result.data.url)
const img = result.data.url;
const dataOfuser = {
user : user?.displayName,
email : user?.email,
phone: data.phone,
city: data.city,
education: data.education,
img: img
}
console.log(dataOfuser)
fetch(`http://localhost:5000/user/:${user.email}`,{
method:"PUT",
headers:{
'Content-Type': 'application/json'
},
body : JSON.stringify(dataOfuser)
})
.then(res => res.json())
.then(data => {
if(data.acknowledged){
toast.success('Profile Updated')
}
})
}
})
};
these are the code from mongodb
app.put('/user/:email',async(req,res)=>{
const email = req.params.email;
const user = req.body;
const filter = { email: email };
const options = { upsert: true };
const updateDoc = {
$set: user,
};
const result = await userCollection . updateOne ( filter , updateDoc , options);
res.send(result);
});

You could try to send email and user as body and
app.put("/user/email", async (req, res) => {
const { dataOfuser } = req.body; //this finds all
const { email, user, phone, city, etc} = dataOfuser; //this extracts the values, but probably better to send each values by themselves
You can also just send user and email etc on their own, instead of as one object:
body: JSON.stringify({ user, email, phone, city, education, img })
You can also try to add curlybraces around dataOfuser in the body: JSON.stringify({ dataOfuser })
const res = await userCollection
.updateOne(
{ email: email} *find the user by his email*
{ $set: {email: email, phone: phone, city: city etc.}}) *set email to email from body*
})
You should also have default value in inputs as their current value, so the fields doesn't get overwritten as null or blank

Related

NEXT JS req.body undefined

not sure what I'm doing wrong?
I'm getting undefined when trying to upload my form data to my supabase the data is coming to the API undefined but when I pass it to the function it prints what I want to send to the API in my submit handler.
export const Quote = () => {
const [formIsValid, setFormIsValid] = useState(false);
//----------------------------_FORM VALIDATION------------------------------------
const {
value: firstName,
inputBlurChangeHandler: firstNameBlur,
isValid: firstNameValid,
hasError: firstNameInputHasError,
valueChangeHandler: firstNameChangeHandler,
reset: resetFirstName,
} = useInput((value) => value.trim() !== "");
**hooks & useEffect removed to shorten question they are same as above but different names**
console.log(formIsValid, "FORM IS VALID");
const formSubmitHandler = async (event) => {
event.preventDefault();
//UNDEFINEDS
await fetch("api/dbhandler", {
method: "POST",
body: {
firstname: firstName,
secondname: secondName,
street: streetAddress,
phone: phoneNumber,
email: emailAddress,
postal: postalCode,
about: quoteDescription,
},
headers: {
"Content-Type": `text/plain`,
},
});
};
API is coming as undefined in req. body but if I console log in the submit handler values are being passed to the function not sure what I am doing wrong
import { supabase } from "../../utils/supabaseClient";
const supabaseApiHandler = async (req, res) => {
console.log(req.body.firstname);
if (req.method === "POST") {
const firstname = req.body.firstname;
const secondname = req.body.secondname;
const email = req.body.email;
const street = req.body.street;
const postal = req.body.postal;
const phone = req.body.phone;
const about = req.body.about;
const { data, error } = await supabase.from("quotes").insert([
{
firstname,
secondname,
email,
street,
postal,
phone,
about,
},
]);
}
res.status(200).json({ name: "test" });
};
export default supabaseApiHandler;
If you have the body parser disabled in the API route, req.body will be empty.
I accidentally left this code in without using another body parser.
export const config = {
api: {
bodyParser: false,
},
};

how can i do Multiple Request using Promise.all using this parameters?

today I had some problems with my code.. the thing is I have to create a multiple POST request to the API to pass users to a group, so.. the API request is:
POST /users/user-group-membership
{
"userId": "string",
"groupId": 0,
"isActive": true,
}
Basically i have to grab from the users table the userId from each user and for each userId create a multiple request... so what i did was:
const moveTogroup = async (
token: string,
userId: string,
groupId: number,
): Promise<any> => {
const res = await axios({
method: 'POST',
url: `${API}/users/user-group-membership`,
data: { userId: userId, groupId: groupId },
headers: {
Authorization: `Bearer ${token}`,
},
});
const { data } = res;
return data;
};
export const moveAllGroup = (
token: string,
): ThunkAction<void, State, null, UsersActions> => {
return async (dispatch, getState) => {
const { userId, groupId } = getState().FleetUsers;
const convert = userId.toString();
console.log(convert);
dispatch(moveUserToGroupRequest());
try {
const userPromises = userId.map(() =>
moveTogroup(token, convert, groupId),
);
const move = await Promise.all(userPromises);
console.log('moving:', move);
dispatch(moveUserToGroupSuccess(move));
Swal.fire('Saved', 'Your Changes has been saved', 'success');
} catch (error) {
dispatch(moveUserToGroupFailure(error));
Swal.fire('Error', error, 'error');
}
};
};
But as you see this only works for one userId, I grabbing from the state the userId and the groupId, converting the userId to string, and voila is working perfectly, only what I want is depending how much userId I have in the state replied to the request for creating multiple requests and when the user selects in table 2 or 3 users, he or she can move them easily.
If your userId var contains all userIds, you must map it to recover specific information about each userId :
userId.map((elt) => {
const convert = elt.toString();
moveTogroup(token, convert, groupId),
});

MissingPasswordError: No password given

I can signup users just fine on my website, but when I test it with Postman I get this error:
MissingPasswordError: No password given
I also cannot login because the password/username combination is incorrect, so there's definitely something wrong but I can't for the life of me figure out what.
This is my html input field for the password:
<input type="password" class="input--text" name="password" id="password">
signup.js with my fetch function:
const btnSignup = document.querySelector('.btn').addEventListener('click', function () {
let username = document.querySelector('#username').value;
let password = document.querySelector('#password').value;
let bday = document.querySelector('#bday').value;
fetch('http://localhost:3000/users/signup', {
method: "post",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'username': username,
'password': password,
'bday': bday
})
}).then(response => {
return response.json();
}).then(json => {
if (json.status === 'success') {
let feedback = document.querySelector('.alert');
feedback.textContent = "Sign up successful!";
feedback.classList.remove('hidden');
}
})
})
And this is my signup function in my auth.js controller:
const signup = async (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
const bday = req.body.bday;
const user = new Users({
username: username
});
/*user.bday = bday;*/
await user.setPassword(password);
await user.save()
.then(result => {
console.log(result.id);
let token = jwt.sign({
id: result._id
}, "{this is a secret}");
res.json({
'status': 'success',
'data': {
'token': token
}
})
}).catch(error => {
res.json({
'status': 'error'
})
});
}
I've added bodyParser, made sure the name for my input fields are correct, ...
Solved! Turns out my code was correct, but I forgot to set the raw body in Postman to JSON (default was text).

When I update one value of a users object, all other values are deleted in database. What can I do about this?

I am working on a school project with a team of developers. We have created a page where the users have a profile and that profile can be updated. We have come across a bug when a user updates its information. If I update my city for example, then all other information about my user disappears. I have to update the other fields as well, otherwise the database will only store the city that I recently updated.
What I want is that the information I filled in when I created my user is saved, besides from the information I change when I update my user.
Before update: {"username":"bobox","email":"bobox#hotmail.com","password":"test234","gender":"Man","age":"17","city":"Jönköping","games":"Battlefield V","usernameDiscord":"bigbox","usernameSteam":"bigbox","usernameOrigin":"bobox","_id":"wTs8IyRmcA40f3VN"}
After update: {"username":"bobox","email":"bobox#hotmail.com","password":"test234","gender":"","age":"","city":"New York","games":"","usernameDiscord":"","usernameSteam":"","usernameOrigin":"","_id":"wTs8IyRmcA40f3VN"}
Here is the code. I am thankful for all help. If there is anything else you need to know, just let me know.
Updating a user:
script.js
async function updateUser(age, city, gender, games, discord, steam, origin) {
const id = localStorage.getItem("userId")
const response = await fetch('http://localhost:8080/users/' + id, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
age: age,
city: city,
gender: gender,
games: games,
usernameDiscord: discord,
usernameSteam: steam,
usernameOrigin: origin
})
})
console.log(response)
const data = await response.json()
console.log(data)
}
function updateUsersIndex() {
let updateProfileBtn = document.querySelector(".Profile-Right__Update")
console.log(updateProfileBtn)
updateProfileBtn.addEventListener("click", async(event) => {
console.log("hej")
event.preventDefault()
const age = document.querySelector(".Age__Input").value
const city = document.querySelector(".City__Input").value
const gender = document.querySelector(".Gender__Input").value
const discord = document.querySelector(".Discord__Input").value
const steam = document.querySelector(".Steam__Input").value
const origin = document.querySelector(".Origin__Input").value
const games = document.querySelector(".Profile-Right__Select-Game").value
const hidden = document.querySelector(".hidden")
const updateUsers = await updateUser(age, city, gender, games, discord, steam, origin)
})
}
updateUsersIndex()
let profileUpdateBackBtn = document.querySelector(".Profile-Right__Back")
profileUpdateBackBtn.addEventListener("click", async(event) => {
event.preventDefault()
let updateProfile = document.querySelector(".Update-Profile")
let profile = document.querySelector(".Profile__Wrappe")
profile.classList.toggle("Hidden")
updateProfile.classList.toggle("Hidden")
})
app.js:
app.patch('/users/:id', async(req, res) => {
const result = await collectionsNEDB.users.update({ _id: req.params.id }, {
$set: {
"age": req.body.age,
"city": req.body.city,
"gender": req.body.gender,
"games": req.body.games,
"usernameDiscord": req.body.usernameDiscord,
"usernameSteam": req.body.usernameSteam,
"usernameOrigin": req.body.usernameOrigin
}
})
console.log(req.params.id)
res.json(result)
})
Creating a user:
script.js
async function createUser(username, email, password, repeatPassword, games, usernameDiscord, usernameSteam, usernameOrigin) {
const response = await fetch('http://localhost:8080/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: username,
email: email,
password: password,
repeatPassword,
games: games,
usernameDiscord: usernameDiscord,
usernameSteam: usernameSteam,
usernameOrigin: usernameOrigin
})
})
console.log(response)
const data = await response.json()
if (response.status == 200) {
console.log(data.message)
if (data.message == "SUCCESS") {
console.log("Great")
let Success = document.querySelector(".Success")
Success.innerHTML = "Användare skapad!"
alert("Användare skapad!")
}
} else {
const data = await response.json()
const p = document.querySelector("p")
p.innerHTML = ""
for (let i = 0; i < data.errors.length; i++) {
const error = data.errors[i]
console.log(data.errors)
switch (error) {
case "ERROR_USER_ALREADY_EXISTS":
const hidden = document.querySelector(".Error")
hidden.classList.toggle("Hidden")
hidden.innerHTML = "Användarnamnet existerar redan!"
break;
case "ERROR_EMAIL_ALREADY_EXISTS":
const hiddenEmail = document.querySelector(".Error__Email")
hiddenEmail.classList.toggle("Hidden__Email")
hiddenEmail.innerHTML = "E-mail existerar redan!"
break;
case "ERROR_PASSWORD_MISMATCH":
const hiddenPassword = document.querySelector(".Error__Password")
hiddenPassword.classList.toggle("Hidden__Password")
hiddenPassword.innerHTML = "Lösenordet matchar inte"
break;
}
}
}
}
function init() {
let form = document.querySelector("#Reg-Form-1")
form.addEventListener("submit", async(event) => {
event.preventDefault()
const username = form.querySelector(".username").value
const email = form.querySelector(".email").value
const password = form.querySelector(".password").value
const repeatPassword = form.querySelector(".repeat-password").value
const games = form.querySelector(".gejms").value
const usernameDiscord = form.querySelector(".usernameDiscord").value
const usernameSteam = form.querySelector(".usernameSteam").value
const usernameOrigin = form.querySelector(".usernameOrigin").value
const hidden = document.querySelector(".hidden")
const createUsers = await createUser(username, email, password, repeatPassword, games, usernameDiscord, usernameSteam, usernameOrigin)
})
}
init()
app.js:
app.post("/register", async(req, res) => {
let user, email
if (process.env.NODE_ENV == "development") {
user = await collectionsNEDB.users.find({ username: req.body.username })
email = await collectionsNEDB.users.find({ email: req.body.email })
} else {
dataUser = await Database.collections.users.find({ username: req.body.username })
dataEmail = await Database.collections.users.find({ email: req.body.email })
user = await dataUser.toArray()
email = await dataEmail.toArray()
}
let errors = []
if (req.body.password !== req.body.repeatPassword) {
errors.push("ERROR_PASSWORD_MISMATCH")
} else if (user == false) {
if (email == false) {
let newUser = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
gender: "",
age: "",
city: "",
games: req.body.games,
usernameDiscord: req.body.usernameDiscord,
usernameSteam: req.body.usernameSteam,
usernameOrigin: req.body.usernameOrigin
}
if (process.env.NODE_ENV == "development") {
const result = await collectionsNEDB.users.insert(newUser)
res.status(200).json({ message: "SUCCESS" })
} else {
let db = await Database.connect()
let users = db.collection("users")
const result = await users.insert(newUser)
res.status(200).json({ message: "SUCCESS" })
console.log(result)
}
} else {
errors.push("ERROR_EMAIL_ALREADY_EXISTS")
}
} else {
errors.push("ERROR_USER_ALREADY_EXISTS")
}
if (errors.length > 0) {
res.status(400).json({ errors: errors })
}
})

Create user with firebase admin sdk that can signIn using email and password

I'm using firebase admin SDK on cloud functions to create users using
admin.auth().createUser({
email: someEmail,
password: somePassword,
})
now I want user to signIn using signInWithEmailAndPassword('someEmail', 'somePassword') but I cannot.
I get the following error
{code: "auth/user-not-found", message: "There is no user record corresponding to this identifier. The user may have been deleted."}
There doesn't seem to be a reason to Stringify/Parse. This worked after I struggled with an unrelated typo...
FUNCTION CALL FROM REACT JS BUTTON CLICK
<Button onClick={() => {
var data = {
"email": "name#example.com",
"emailVerified": true,
"phoneNumber": "+15551212",
"password": "randomPW",
"displayName": "User Name",
"disabled": false,
"sponsor": "Extra Payload #1 (optional)",
"study": "Extra Payload #2 (optional)"
};
var createUser = firebase.functions().httpsCallable('createUser');
createUser( data ).then(function (result) {
// Read result of the Cloud Function.
console.log(result.data)
});
}}>Create User</Button>
And in the index.js in your /functions subdirectory:
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp();
// CREATE NEW USER IN FIREBASE BY FUNCTION
exports.createUser = functions.https.onCall(async (data, context) => {
try {
const user = await admin.auth().createUser({
email: data.email,
emailVerified: true,
password: data.password,
displayName: data.displayName,
disabled: false,
});
return {
response: user
};
} catch (error) {
throw new functions.https.HttpsError('failed to create a user');
}
});
Screen shot of console output
In 2022 there still is no method built into the Admin SDK that would allow to create users in the emulator.
What you can do is to use the REST API of the emulator to create users there directly. The API is documented here: https://firebase.google.com/docs/reference/rest/auth#section-create-email-password
Provided you have got and nanoid installed you can use the following code to create users in the emulator.
import { nanoid } from 'nanoid'
import httpClientFor from '../lib/http-client/client.js'
const httpClient = httpClientFor('POST')
export const createTestUser = async ({ email = `test-${nanoid(5)}#example.io`, password = nanoid(10), displayName = 'Tony' } = {}) => {
const key = nanoid(31)
const { body: responseBody } = await httpClient(`http://localhost:9099/identitytoolkit.googleapis.com/v1/accounts:signUp?key=${key}`, {
json: {
email,
password,
displayName
}
})
const responseObject = JSON.parse(responseBody)
const { localId: userId, email: userEmail, idToken, refreshToken } = responseObject
return { userId, userEmail, idToken, refreshToken }
}
Please note: As there is no error handling implemented, this snippet is not suitable for production use.
Try like that
And please be ensure that user is created from the panel
admin.auth().createUser({
email: "user#example.com",
emailVerified: false,
phoneNumber: "+11234567890",
password: "secretPassword",
displayName: "John Doe",
photoURL: "http://www.example.com/12345678/photo.png",
disabled: false
})
.then(function(userRecord) {
// See the UserRecord reference doc for the contents of userRecord.
console.log("Successfully created new user:", userRecord.uid);
})
.catch(function(error) {
console.log("Error creating new user:", error);
});
Just in case anyone else comes across this I was able to fix it with the help of this.
Here is a working example inside of an onCreate cloud function:
exports.newProjectLead = functions.firestore
.document('newProjectForms/{docId}')
.onCreate(async (snapshot) => {
const docId = snapshot.id
// this is what fixed it the issue
// stringify the data
const data = JSON.stringify(snapshot.data())
// then parse it back to JSON
const obj = JSON.parse(data)
console.log(obj)
const email = obj.contactEmail
console.log(email)
const password = 'ChangeMe123'
const response = await admin.auth().createUser({
email,
password
})
data
const uid = response.uid
const dbRef = admin.firestore().collection(`clients`)
await dbRef.doc(docId).set({
id: docId,
...data,
uid
}, {
merge: true
})
console.log('New Client Created')
})

Categories

Resources