0

NodeJS アプリケーションの単純なログイン システムに取り組んでいます。このために、「企業」という 1 つのオブジェクトがユーザーの配列を保持する構造を作成しました。これは、corporation オブジェクトを使用してアプリケーション セッション データを保存する予定があるためです。

{
    "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"
        }
    ]
}

問題は、(ログイン シナリオで) ユーザーの後にクエリを実行すると、予想どおり、クエリが企業オブジェクト全体を返すことです。したがって、1 人だけが必要な場合でも、すべてのユーザーを公開しています。セキュリティに関しては大したことではないと思いますが、パフォーマンスの方が心配です。以下は現在のクエリであり、要求されたユーザー以外のすべてのユーザーを削除する非常に醜い方法です。

さまざまなアサートは無視してください。コードは非常に進行中です.. :)

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

If you're using MongoDB 2.2 or greater you can just use the "$" positional operator.

The following query worked for me :

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

Although I would agree with the other comments that you should probably reconsider your schema...

于 2013-05-25T14:45:18.460 に答える