I make an edit profile request where is possible to edit one or more fields.
And when i make put request and want change only one field, every undefined field becomes null. How to pass undefined field? Every not mentioned field in request saves its value
//update profile
app.put("/id/:id", async (req,res) => {
try{
const {id} = req.params;
const {username, email, userdescription, photo_url} = req.body;
const ifEmailExists = await isEmailAvailable(email)
const ifUsernameExists = await isUsernameAvailable(username)
if(ifEmailExists && ifUsernameExists){
const updUser = await pool.query(
"UPDATE users SET (username, email, userdescription, photo_url) = ($1, $2, $3, $4) WHERE id = $5",
[username, email, userdescription, photo_url, id]);
res.json(`User data was updated successfully !`);
} else { if(!ifUsernameExists&& !ifEmailExists){
res.json({"msg": "Username and email are already used !"});}
else {
if(!ifEmailExists)
res.json({"msg": "Email is already used !"});
else { if(!ifUsernameExists){
res.json({"msg": "Username is already used !"});}
}
}
}
}catch(err){
console.error(err.message);
}
})
Related
This is the scenario where I am storing several attributes into the database. Now, while I fetch the response I don't want the exact attribute name what's already stored in Db. For eg, below is my code. Here, I have stored fields as 'ca_xyz'.Now while fetching the response I want only only 'xyz' as fieldname. Can anyone help me?
// --------adding customer group--------
const addCustomerGroup = async(req,res,next) => {
try{
console.log(req.body)
let data = await Group.create({
cg_name:req.body.name,
cg_description:req.body.description,
cg_is_active: req.body.is_ctive,
cg_created_by: req.body.created_by,
cg_modified_by: req.body.modified_by
})
var newData = {};
for (const [key, value] of Object.entries(data)) {
newData[key.substr("cg_".length)] = value;
}
console.log(newData)
res.send({
status:"success",
message:"Added customer group"
})
}
catch(error){
console.log(error)
res.send({
status:"failed",
message:"An error occurred"
})
}
}
i am new in NodeJs development,
i want to ask, surely this is kinda basic, but i dont know how to do it.
i have a task to read request one field that can filled with multiple values,
on json array like this :
{
"email" : "first#mail.com" , "second#mail.com", "third#mail.com"
}
how to get each value from that "email" field and processing it to some function ?
i have a query select to get username from one table
select username from [dbo].[users] where email=#email (first, second, and third)
this is my code for now only that read one value, not multiple :
async getValueFunction(req, res) {
res.setHeader('Content-Type', 'application/json');
try {
if (req.body.email != "") {
const pool = await poolPromise
const result = await pool.request()
.input('email', sql.VarChar, req.body.email)
.query(queries.getUserScoreByEmail)
var showUserScore = result.recordset;
res.json(showUserScore);
} else if (req.body.email == "") {
const pool = await poolPromise
const result = await pool.request()
.query(queries.getUserScore)
var showAllUserScore = result.recordset;
res.json(showAllUserScore);
}
} catch (error) {
res.status(500)
res.send(error.message)
}
}
how to do the loop (iteration) and collect the result/recordset before send as one response (json) ??
You should update your structure because it is not an key value pair.
What you can do is storing the E-Mail Adresses in an Array like this
const data ={
"email" : ["first#mail.com" , "second#mail.com", "third#mail.com" ]
}
And then you access it with data.email
I want to save token generated into the user's confirmed email column. The token is part of the confirmation link that will be sent to the user so that when the user clicks on the link I can check if it matches, then updates it to "activated".
Now the problem is I can't figure out how to save it in the ConfirmEmailLink method .
async register(createDTO: CreateUserDto) {
const { email } = createDTO;
const user = await this.userModel.findOne({ email })
if (user) {
throw new HttpException('User already exists', HttpStatus.BAD_REQUEST);
}
const createdUser = new this.userModel(createDTO);
var newUser = await createdUser.save();
await SendEmail(createDTO.email, await **this.ConfirmEmailLink(createdUser._id)**, createDTO.email);
return this.sanitizeUser(createdUser);
//return null;
}
In the above code there is ConfirmEmailLink that is a parameter to SendEmail method
async ConfirmEmailLink(userId: string) {
const id = v4();
var payload = { userId: userId };
var secret = process.env.JWT_SIMPLE_TOKEN;
var token = jwt.encode(payload, secret);
console.log("This is uuid", userId);
var link = `${process.env.HOST}/user/confirm/${token}/${id}`;
let user = await this.userModel.findById(userId);
if (!user) {
throw new HttpException("Registration not complete, try again or contact admin", HttpStatus.NOT_FOUND);
}
**//This is where the problem is, I want to save the token in ConfirmEmail column**
await this.userModel.updateOne({confirmEmail: token});
return link;
}
I will appreciate your suggestions or if there is a better way to do this
Thanks
updateOne needs 2 parameters, a filter to identify which document to modify, and a update indicating what to do.
.updateOnde({"_id":userId},{"$set":{"confirmEmail": token}})
I'm writing an API that gets past transactions on the Stellar network for a user, looks up the corresponding users in my database, and put's it all together into a JSON (to respond to the request - later).
Problem: looking up the username corresponding to the accountID ("from" field) is an async method with mongoose and only returns data after the JSON has been assembled.
I've tried to use async/await, promises, .thens but nothing seems to work.
server.payments()
.forAccount(accountId)
.cursor('now')
.order('desc')
.limit(2)
.call()
.then(function (page) {
var history = []
for(var i = 0; i<page.records.length; i++){
var obj = page.records[i]
//Get the username corresponding to the key from my database
//FIXME
var username
findUser(obj["from"]).then(result => {
username = result
})
var payment = {
"currency":obj["asset_code"],
"from": obj["from"],
"username":username,
"amount": obj["amount"],
"timestamp":obj["created_at"]
}
history.push(payment)
}
console.log(history)
//console.log(JSON.stringify(history))
})
.catch((err) => {
console.log(err)
})
async function findUser(senderKey){
var user = await mongoose.User.findOne({publicKey: senderKey})
console.log(user.username)
return user.username
}
Expected result: findUser returns value, payment variable uses it and gets logged together.
What happens: findUser starts looking for data, payment variable gets put together (username as undefined) and logged, findUser returns data.
Here's the log: (spiderman is the actual username from my database)
[ { currency: 'MEUR',
from: 'GACRQARPR2OMWRG6IH7HM5DYTA3FMM6UKA7NKS4BIJIADRIKFRPAIE7G',
username: undefined,
amount: '3.0000000',
timestamp: '2019-05-07T13:37:04Z' },
{ currency: 'MEUR',
from: 'GACRQARPR2OMWRG6IH7HM5DYTA3FMM6UKA7NKS4BIJIADRIKFRPAIE7G',
username: undefined,
amount: '2.0000000',
timestamp: '2019-05-07T13:34:21Z' } ]
spiderman
spiderman
Highlight recommend, you can make it easy with async/await syntax for your case.
You will wait until the server responses the page, then each of obj in page.records (.map or .forEach... will make you some mess), you wait for findUser function returns the username, then do your business.
try {
const page = await server.payments()
.forAccount(accountId)
.cursor('now')
.order('desc')
.limit(2)
.call()
const history = [];
for (const obj of page.records) {
const username = await findUser(obj["from"]);
const payment = {
"currency": obj["asset_code"],
"from": obj["from"],
"username": username,
"amount": obj["amount"],
"timestamp": obj["created_at"]
}
history.push(payment)
}
console.log(history)
} catch (e) {
console.log(e)
}
Remind: await expression only allowed within an async function.
You can use the new "for of" loop along with async await :-
server.payments()
.forAccount(accountId)
.cursor('now')
.order('desc')
.limit(2)
.call()
.then(async function (page) {
var history = []
for(const obj of page.records) {
const username = await findUser(obj["from"]);
var payment = {
"currency":obj["asset_code"],
"from": obj["from"],
"username":username,
"amount": obj["amount"],
"timestamp":obj["created_at"]
}
history.push(payment)
}
console.log(history)
//console.log(JSON.stringify(history))
})
.catch((err) => {
console.log(err)
})
You need a conditional that checks whether the function you are awaiting has completed
async function findUser(senderKey){
var user = await mongoose.User.findOne({publicKey: senderKey})
if (user){
console.log(user.username)
return user.username
}
}
There's a block of code that uses axios-mock-adapter and returns an object via a GET request:
mock.onGet('/api/auth').reply((config) => {
const data = JSON.parse(config.data);
const {email, password} = data;
const user = _.cloneDeep(authDB.users.find(_user => _user.data.email === email));
const error = {
email : user ? null : 'Check your username/email',
password: user && user.password === password ? null : 'Check your password'
};
if ( !error.email && !error.password && !error.displayName )
{
delete user['password'];
const access_token = jwt.sign({id: user.uuid}, jwtConfig.secret, {expiresIn: jwtConfig.expiresIn});
const response = {
"user" : user,
"access_token": access_token
};
return [200, response];
}
else
{
return [200, {error}];
}
});
User is a JSON object with various amounts of values. How is this possible? What would it look like in the URL? I'm studying the code block to learn how to do it without axios-mock-adapter.