2017-09-08 6 views
0

私はmongoとmongooseを新しくしました。mongoose mongodb query find

私は、リレーショナルデータベースに簡単なクエリを実行したいが、私はここのmongoに

を行うための強力な問題を抱えているが、私は、スキーマです:

const GroupSchema = new Schema({ 
    name: { type: String , required:true}, 
    image: { type: String , required:true}, 
    location : {type:String , required: true}, 
    locationCode: {type:String , required:true }, 
    created: {type:Date, default:Date.now() , required:true }, 
    createdBy: {type: Schema.Types.ObjectId , ref:'User' , required:true}, 
    //category: [{type:String,enum:[ config.TYPES ]}], 
    pendingUsers: [ 
     { text:String, 
      user:{type: Schema.Types.ObjectId , ref: 'User'} 
     } 
    ], 
    rejectedUsers: [ {type: Schema.Types.ObjectId , ref: 'User'} ], 
    users: [ {type: Schema.Types.ObjectId , ref: 'User' , required:true } ], 
    adminUsers:[{type:Schema.Types.ObjectId , ref:'User', required:true}], 
    events :[Event], 
    activity:[Activity] 
}) 

と私、私のコントローラファイル私は、次の操作を行いたいです問い合わせ:私は_idグループIDと一致し、は(のuserIdがpendingUsersに存在するか、またはユーザーIDがrejectedUsersに存在するか、ユーザーIDがユーザーに存在するかのレコードを取得する必要があります

let groupId = '123123hgvhgj 
let userId = 'asdfsadf3434 

Group.find() 
    .where('_id').equals(groupId) 
    .where('pendingUsers.user') 
    .in(userId) 
.where('users') 
    .in(userId) 
.where('adminUsers') 
    .in(userId) 
.where('rejectedUsers') 
    .in(userId) 
    .exec(function (err, records) { 
     //make magic happen 
     console.log(records) 
    }); 

ユーザーIDがadminUsersに存在します)

私は単純なクエリであると思われますが、レコードが返されるべきときに空を返します。クエリに何か問題がありますか?マングースは(docs) いくつかのシンプルで+または操作をサポートすると思われる場合でも、あなたはまだそれにいくつかの純粋なMongoDBのクエリを混在させる必要があるだろうかのように私には思える

おかげ

答えて

0
Group.find({ 
     $and: [ 
      { _id: groupId}, 
      { 
       $or: [ 
        { "pendingUsers": { $elemMatch: { "user": userId } } }, 
        //{ 'pendingUsers.user' : { $elemMatch: {userId} } }, 
        { rejectedUsers: { $elemMatch: {userId} } }, 
        { users: { $elemMatch: {userId} } }, 
        { adminUsers: { $elemMatch: {userId} } }, 
       ] 
      } 
     ] 
    }) 
0

これを考慮すると、私は純粋なmongodbスタイルのクエリに行きます。この一つは、あなたのニーズを(未テスト)収まる必要か、少なくとも正しい方向にあなたをポイントします:

Group.find({ 
    $and: [ 
     {_id: groupId}, 
     { 
      $or: [ 
       { pendingUsers.user: { $elemMatch: {userId} } }, 
       { rejectedUsers: { $elemMatch: {userId} } }, 
       { users: { $elemMatch: {userId} } }, 
       { adminUsers: { $elemMatch: {userId} } }, 
      ] 
     } 
    ] 
}); 
+0

おかげで、私はそれを少し変更する必要があります: 'Group.find({ \t \t $をし、 [ \t \t \t {_id:のgroupId}、 \t \t \t { \t \t \t \t $または:[ \t \t \t \t \t { "pendingUsers":{$ elemMatch:{ "ユーザー":userIdを}}}、 \t \t \t \t \t // { 'pendingUsers.user':{$ elemMatch:{userIdを}}}、 \t \t \t \t \t {rejectedUsers:{$ elemMatch:{にuserId}}}、 \t \t \t \t \t {ユーザー:{$ elemMatch:{にuserId}}}、 \t \t \t \t \t {アクセスadminusers:{$ elemMatch。 {にuserId}}}、 \t \t \t \t] \t \t \t} \t \t] \t}) ' – bcg