6

ユーザーとデバイスの間に1対多の関係があります(ユーザースキーマに埋め込まれています)

var UserSchema = new Schema({
    devices: [DeviceSchema] //list of devices for the user      
})

var DeviceSchema = new Schema({
    deviceRegistrationId: String,
    deviceOSType: String
});

デバイスをユーザー コレクションに追加するために、エクスプレス POST /api/device (ユーザー ID はヘッダーで提供されます) で Rest 呼び出しを行っています。デバイスがユーザー モデルにまだ存在しない場合にのみ、デバイスを追加したいと考えています。ポストコールの本文は次のようになります

{ deviceRegistrationId : "xx2233", 
  deviceOSType: "Android"
}

ヘッダーのユーザー ID がユーザー コレクションに存在するかどうかを確認し、存在する場合は、デバイスがまだデータベースにない場合にのみデバイスを追加します。

私の現在の実装は次のようなものです。

var userId = req.header('UserId');
        var deviceRegistrationId = req.body.deviceRegistrationId;
        User.findById({_id: userId}, function(err, user) {
             if (user && user!==undefined) {
                if (UserController.containsDevice(user.devices, deviceRegistrationId)) {
                    console.log('contains device - do nothing ');
                    res.send({errors: [{code: 666, message: 'Device Already Registered'}]})
                } else {
                    user.devices.addToSet(req.body);
                    user.save();
                    //todo check what to send back.. 
                    res.send(user);
                }
             } else {
                res.send({errors: [{code: 666, message: 'User not found in the database'}]});
             }

             if (err) 
                res.send({errors: [{code: 666, message: 'Unexpected issue in User Collection'}]});
        });


UserController.containsDevice = function(devices, deviceRegistrationId){
        console.log('UserController::containsDevice devices: ' + JSON.stringify(devices) + 
                    " deviceRegistrationId: " + deviceRegistrationId);
        var strDeviceRegistrationId = "" + deviceRegistrationId;
        for (var i = 0; i < devices.length; i++) {
            console.log(' device id :' + JSON.stringify(devices[i].deviceRegistrationId)); 
            if (devices[i].deviceRegistrationId == strDeviceRegistrationId) {
                console.log('id matched');
                return true;
            }
        }

            return false;          

    }

デバイスが既に存在するかどうかを判断する方法がデバイス配列ではないかどうかを確認したかったのです。

4

1 に答える 1

8

次のように、ドット区切りのパスをクエリで使用できますUser.find({'devices.deviceRegistrationId': deviceRegistrationId})。そのクエリがどのドキュメントとも一致しない場合、そのデバイスを持っているユーザーはいません。mongo はdevices、このようなクエリが与えられたときに配列のすべてのメンバーをテストするのに十分スマートであることに注意してください。特定のユーザーを確認する場合は、クエリ条件にユーザー ID を追加することもできます。

于 2013-07-17T04:02:22.053 に答える