0

I'm working on a simple login system for my NodeJS application. For this I have created a structure where one object, a "corporation", holds an array of users. I've done because I plan to use the corporation object to store application session data.

{
    "name": "My Corporation",
    "prefix": "MYCORP",
    "users": [
        {
            "username": "some@user.com",
            "password": "974dae09cd5869958c19e1742117c2f8",
            "name": "Freddly the User"
        },
        {
            "username": "other@user.com",
            "password": "974dae09cd5869958c19e1742117c2f8",
            "name": "Max the Admin"
        }
    ]
}

The problem is when querying after a user (in a log-in scenario) the query, as expected, returns the entire corporation object. Thus I'm exposing all users even though I only want one. As far as security is concerned I guess it isn't a big deal, but I'm more worried about performance. Below is the current query and a very ugly way to delete all users but the one requested.

Ignore the different asserts. Code is very much work-in-progress .. :)

db.collection('kat_corp', function (err, collection) {
    try {
        assert.equal(null, err);

        collection.findOne({
            users: {
                $elemMatch: {
                    username: user.username
                }
            }
        }, function (err, result) {
            if (err) callback(err, false);

            // Delete all other users from the to-be session object
            for (var i = 0; i < result.users.length; i++) {
                if (result.users[i].username != user.username) {
                    delete result.users[i];
                }
            }
            // Will be replaced with success callback
            console.log(result);
        });

    } catch (err) {
        callback(err, false);
    }
});
4

1 回答 1

2

如果您使用的是 MongoDB 2.2 或更高版本,则可以使用"$" 位置运算符

以下查询对我有用:

db.collection('kat_corp', function (err, collection){
    collection.findOne({"users.username":user.username}, {'name':1,'users.$': 1}, console.log) 
});

虽然我同意其他评论,您可能应该重新考虑您的架构......

于 2013-05-25T14:45:18.460 回答