I want to create a new user in dynamodb but before that I want to check that user is present in db or not. Here Primary partition key is username. I Want to check both emailId and username in the condition. Both should be unique. For example
user1 user1#gmail.com
user2 user2#gmail.com
user3 user3#gmail.com
Example1 When I create a new user username= user4 and emailId=user1#gmail.com It should not create a new user because emailId is already present.
Example2 When I create a new user username= user1 and emailId=user4#gmail.com It should not create a new user because username is already present.
So these are the scenarios. Can anybody tell what is the best solution for this?
I found the solution using scan method
const AWS = require('aws-sdk');
const dynamoDb_DocumentClient = new AWS.DynamoDB.DocumentClient();
let params = {
TableName: "OP-User",
ProjectionExpression: 'userName, emailAddress',
FilterExpression: "userName = :userName OR emailAddress = :emailAddress",
ExpressionAttributeValues: {
":userName": "user1",
":emailAddress": "user111#asurion.com"
}
};
dynamoDb_DocumentClient.scan(params, function (err, data) {
if (err) {
console.log("err: " + err);
}
console.log("data: " + data);
});
Can we have another solution for this ? using Query, Indexname? like this.
Any suggestion would be appreciated.
Thanks,
Use AWS DynamoDB Conditional Expressions to compare Username and ID attributes, before creating and item.
Related
async function update(id, userParam) {
const user = await User.findById(id);
// validate
if (!user) throw 'User not found';
if (user.username !== userParam.username && await User.findOne({ username: userParam.username })) {
throw 'Username "' + userParam.username + '" is already taken';
}
// hash password if it was entered
if (userParam.password) {
userParam.hash = bcrypt.hashSync(userParam.password, 10);
}
// copy userParam properties to user
Object.assign(user, userParam);
await user.save();
}
When I send an update request it updates everything in the body. I only need to send userid, username and user role and update to update only those fields. I am very beginner.PLEASE help me to solve my issue
You can find the document and update the field what you want by using "updateOne". for example, here I am going to update User collection's username only. mongodb's "updateOne" will fulfill that task here basically updateOne has 3 parameters.
search the document you can use any filed here I have used the _id field.
{ "_id": "232323"}
second parameater is {$set:{"username":"kalo"} this will set the new value.here you can use any number of fields.
User.updateOne({ "_id": "232323"},{$set:{"username":"kalo"}})
For More mongodb doc
If you are using Mongoose nodejs mongodb ORM read this. This doc says the same thing that I explained.
In your case you can simply use like below instead of await user.save();
await User.findOneAndUpdate({ _id: userid }, { username : username , userid: userid,userrole:userrole})
use the User not user
user.username = user.userParam;
This is the key Line I needed.It solved my issue....Although it's simple answer,it may be useful to some of the beginners like me.
Guys I have some general questions about interacting with my PostgreSQL DB my ExpressJS API and my React Native Frontend.
I managed to write some queries that for example check if the username that is entered in my RN app matches the one that is on the DB and returns its userID.
I know that on my DB every User has its Password that is being stored inside the DB in a hashed way.
How would a Query look like that would return for example the userID as I am doing it but only if the username exists and it matches the Password that is stored on the DB?
Do I need to know how the passwords are hashed on the DB?
The Query for userid:
static getUserId (username, callback) {
db.query(`SELECT userid FROM employee WHERE username = '${username}'`, (err, res)=> {
if(err.error){
return callback(err.error)
} else {
return callback(res)
}
})
}
The passwords are saved in the same employee table under password.
EDIT: I think I can take two WHERE statements like this:
`SELECT userid FROM employee WHERE username = '${username}' AND WHERE password = '${password}'`
but if a User enters his password inside the app it is not hashed so do I need to send the same hash method to compare these values?
Thanks in advance!
Best regards Faded.
You can use bcrypt.js for hashing your passwords.
To hash password in SignUp.js:
app.post('/signup',(req,res,next)=> {
//Password from request body of register request
const myPlaintextPassword = req.body.password
//saltRounds are typically set to 12
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
// Store hash in your password DB with INSERT.
});
}
Now to compare with Hash in Login.js:
app.post('/login',async (req,res,next)=>{
const existingUser = await db.query(`SELECT userid FROM employee WHERE username = '${username}'`, (err, res)=> {
if(err.error){
return callback(err.error)
} else {
return callback(res)
}
})
const valid = await bcrypt.compare(req.body.password, existingUser.password);
if (!valid) {
res.status(401).send('Wrong pass');
return req.next()
}
}
You need to hash the incoming password and compare the two hashes.
That being said: if this is going to be at all used by real people I would suggest using a library to handle your auth instead of writing your own. There are a lot of things that can go wrong to make your application insecure.
I've created a table with the name of user in postgres which contains id, name, family columns (id is auto-increment). The query which I want to insert into the postgres likes the following:
var config = {
user: 'username',
database: 'databaseName',
password: 'password',
host: 'localhost',
port: 5432,
max: 10,
idleTimeoutMillis: 30000
};
const pool = new postgre.Pool(config);
let query = "INSERT INTO user(name, family) VALUES ('name', 'family')";
pool.query(query, [], function (err, result) {
if (err) {
return console.error("error running query", err);
}
console.log("done!");
});
But, I've got the following error:
Syntax error near user
Also, I have tried different approach to send the request liked the following:
const connectionString = "http://localhost:5432/databaseName?username=username&password=password";
const client = new postgre.Client(connectionString);
client.connect();
const query = client.query("INSERT INTO user(id, name, family) VALUES ('name', 'family')");
query.then(x => { console.log("done!")});
query.catch(x => { console.log(x)});
But I've got the following error:
role \"UserName\" does not exist
Also, the UserName (name of the server) in the body of the error is not the same as the username of the database.
I've checked the all possible fallacies such as the correctness of the username and password.
Therefore, the question is what is the problem?
All of these problems come from the table name. As mentioned in this post, the name of user is a reserved name in postgres. Therefore, these errors will be passed if change the name of the user table such as users.
user is a reserved word in PostgreSQL that refers to the currently logged in user. For that reason, in order to be able to use a table with name user, the name must always be inside double quotes - "user".
i am working on node js using dynamoDB with dynamoose. For example, let us assume we have a table Employees in which there is two attributes Branch and Domain. I have a given branch and domain, now i want to get all the employees under either the given branch or the give domain. Can anyone please give an example for above case?
Here is the code to query and scan.
The code connects to DynamoDB local instance.
Employee Schema used:-
Branch - Hash Key
No sort key in the table
Domain - is the attribute
Code:-
var dynamoose = require('dynamoose');
dynamoose.AWS.config.update({
accessKeyId : 'AKID',
secretAccessKey : 'SECRET',
region : 'us-east-1'
});
dynamoose.local();
var Schema = dynamoose.Schema;
var Table = dynamoose.Table;
var Employee = dynamoose.model('employee', { branch: String, domain: String });
Employee.get('UK').then(function (data) {
console.log('Get :' + JSON.stringify(data));
});
Employee.query('branch').eq('UK').exec(function (err, data) {
console.log('Query :' + JSON.stringify(data));
});
Employee.scan('domain').eq('Banking').exec(function (err, data) {
console.log('Scan :' + JSON.stringify(data));
});
Explanation:-
Employee.get(..) - Get the data by hash key
Employee.query (..) - Get the data by hash key along with other attributes as needed
Employee.scan (..) - Get the data based on non-key attributes
I'm working on my first web dev project involving backend work, and i'm giving mongoDB a shot. I'm currently working on a simple admin panel where every user is listed, and by clicking on that user the admin can go in and manually edit their info, update, and return to the master user list to see the changes.
I'm trying to use the collection.save() method to update the existing users, but I've encountered a problem where, instead of just updating, it creates a duplicate copy of the document with a matching _id number. Here is an image illustrating what I mean, and here is all of my code for the update:
router.post('/updateUser', function(req, res) {
var db = req.db;
var collection = req.collection;
var userId = req.body.userId;
var djStatus = req.body.djStatus;
var access = req.body.access;
var firstName = req.body.firstName;
var lastName = req.body.lastName;
var email = req.body.email;
var phone = req.body.phone;
var studentStatus = req.body.studentStatus;
var macIdNum = req.body.macIdNum;
var iclass = req.body.iclass;
var gradYear = req.body.gradYear;
var show = req.body.show;
var blurb = req.body.blurb;
collection.save(
{
_id: userId,
djStatus: djStatus,
access: access,
firstName: firstName,
lastName: lastName,
email: email,
phone: phone,
studentStatus: studentStatus,
macIdNum: macIdNum,
iclass: iclass,
gradYear: gradYear,
show: show,
blurb: blurb
}, function (err, doc) {
if (err) {
res.send('there was a problem updating');
} else {
console.log(doc + ' doc');
res.location('admin/users');
res.redirect('admin/users');
}
});
});
I am really not sure why this is happening. any help would be much appreciated!
From the post, I'm not sure which mongodb driver you're using but save() is probably not used for updating a document in mongodb. There should be an update() function from the mongodb driver you are using. For example, with mongoskin driver, this is the syntax for insert/update:
collection.update(_id: userId, {$set: data}, {safe:true, upsert:true}, function (err, result) {
// check err and result and do something
});