简体   繁体   中英

Checking if user exists in Rethinkdb database

I'm working with rethinkdb to add users to a users table. I have the user being added just fine and I'm seeing the correct data inside of the data explorer. What I'm a little stumped on now is how I can check the database once someone adds a new username to see if it exists or not, and if so, add the new users. I thought I could just grab all the current users from the database and check them in a loop against the new username I'm trying to add. Here is what I'm trying:

router.post('/signup', (req, res) => {

    let newUser      = req.body.username,
        currentUsers = [];

    r.db('base').table('users')
    .then((users) => {
        users.forEach((user) => {
            currentUsers.push(user.username)
        });
    }).then(() => {

        if (currentUsers.length === 0) {
            addUser(req.body);
        }

        currentUsers.forEach((name) => {

            if (newUser !== name) {
                console.log('new user added!');
                addUser(req.body);
            } 

            if (newUser === name) {
                console.log('user exists!');
            }

        }); // end forEach()

    }); // end last .then()


    function addUser(user) {
        Users.create(user, (error, response) => {
            if (error) return res.end();
        });
    } // end addUser(user)


}); // end router.post()

My thought process here was in the database is empty, call the addUser function to add the first username. That works great, but it's when I try to add more than one new user is when things get wonky. Say I have the username Dan in the database. If I try to add Dan again, it runs the addUser function when it shouldn't and the console gives me both messages:

user exists!
new user added!

It will also start to double and triple and etc the database names each time I try to add a new user. What am I doing wrong here? I'm a bit new to rethinkdb, so I'm thinking I just did this the wrong way. Any help I can get would be great. Thanks guys.

Good to know you solved it. But you're fetching all users, putting them temporarily in the server's memory, looping through each user, just to check if the new user exists or not! That's slow, memory-consuming, and unnecessarily.

Here's what you could do better:

  1. Change the primary key of "users" table to "username". Here is how to do so , you will need to use the option primaryKey .
  2. Use the below ReQL to insert new user, which will insert new user in the table only if username doesn't exist :

-

r.db("my_db").table("users").insert(newUser, {conflict: "error"});

All that code done in one line :)

Or, If all you want is just to check if "username" exists without inserting, you can do this:

r.db("my_db").table("users").filter({username: newUserName}).count().eq(1);

Alright. So after some tinkering around and getting help from a work associate, I got this to work as expected after some significant code changes. Turns out that using .map() to loop over users like that was the reason I kept running the function whether the name matched or not. A better approach was to check for the user using if (_.size(users) > 0) {} . I'll post what is working for me below and hopefully this will help someone else down the road.

Things to note in the new code:

  • I created a connect function for our connection.
  • You'll notice _ in places like _.isEmpty(username) . Here I'm using the Lodash library.
  • User.getUser() isn't needed here, but it's used to see the user you add in your browsers console under the network tab.

Working code:

function connect() {
    return r.connect({
        host: config.rethinkdb.host,
        port: config.rethinkdb.port,
        db: config.rethinkdb.db
    });
}

router.post('/signup', (req, res) => {

    const username = _.get(req.body, 'username', '');

    if (_.isEmpty(username)) {
        return res.status(201).json({
            message: 'username cannot be empty'
        });
    }

    return connect()
        .then(connection => {
        return r
        .table('users')
        .getAll(username, { index: 'username'}).run(connection)
        .then((cursor) => cursor.toArray())
        .then((users) => {

            // If user exist return error
            if (_.size(users) > 0) {
                console.log('user already exist');
                return res.status(201).json({
                    message: 'user already exist!'
                });
            };

            Users.create(req.body, (error, user) => {
                if (error) return res.status(500).json({
                    error: error,
                    message: 'Something messed up'
                });

                const userID = user.generated_keys[0];

                Users.getUser(userID, (err, user) => {
                    return res.status(200).json({
                        user: user
                    });
                });
            });
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM