2017-06-24 54 views
-5

什麼基本上,我試圖做的,就是呈現在前端基於用戶是否是該組與否的一部分(react.js)不同的外觀。我試過條件查詢,循環中的前端等什麼是MongoDB中(node.js中)有條件查詢數據的最佳方式?

,你們會解決這個問題的方法呢?

我最後的嘗試是一個聚集,但它不返回任何值:

 Role.aggregate(
     [ 
     { 
      $project: {_id: roleID, 
      UserInRole: { $cond: { 
      if:{ userList: { $in: [userID]}}, then: true, else: false} }} 

     } 
    ] 
      ) 
+0

「基於用戶是否是該組與否的一部分」 - 你可以詳細說說條件,幷包括一些代碼,你試過? –

+0

問題是,無論我嘗試失敗。 – TheGabornator

+0

我想要的是像例如Facebook的。只要你不在一個組中,你就會看到一個連接按鈕。一旦你進入,你會看到離開按鈕。簡單理論背後的過程是什麼? – TheGabornator

回答

1

要拿出一個有效的MongoDB的查詢確定用戶是否是一個組的一部分,需要怎樣的理解你正在構建你的數據庫和組合集合。到結構的一種方式是像這樣:

{ 
    "_id" : ObjectId("594ea5bc4be3b65eeb8705d8"), 
    "group_name": "...", 
    "group_members": [ 
     { 
      "user_id": ObjectId("<same one from users collection"), 
      "user_name": "Alice", 
      "user_profile_picture": "<link_to_imag_url>" 
     }, 
     { 
      "user_id": ObjectId("<same one from users collection"), 
      "user_name": "Bob", 
      "user_profile_picture": "<link_to_imag_url>" 
     }, 
     .... 
    ] 
} 

你組的文件/對象可以擁有的東西屬性,如它的名字,創建日期,說明等,其中的屬性應該是可以使用「group_members」在查詢時查看用戶(基於ID)是否屬於特定組。

MongoDB的$elemMatch運營商似乎是一個很好的選擇,以滿足你的使用情況(如果您使用的是類似組數據結構示例之一。再往下是$ elemMatch頁面上是Array of Embedded Documents的部分。你可以做一個查詢像:

db.groups.find({ 
    _id: ObjectId("<id of group you're checking"), 
    group_members: { 
     $elemMatch: { user_id: ObjectId("<user id of user you're checking>") } 
    } 
}) 

,將返回1分或0的結果1,如果不存在具有該_idgroup_members陣列包含具有指定的用戶ID的元素的基團,否則爲0。

現在在Node中使用它,你可以使用MongoDB NodeJS Driver在與Express Web服務器結合:

var MongoClient = require('mongodb').MongoClient 
var ObjectID = require('mongodb').ObjectID; 
var express = require('express'); 
var app = express(); 
var bodyParser = require('body-parser'); 

app.use(bodyParser.urlencoded({extended: true})); 
app.use(bodyParser.json()); 

// Connection URL 
var url = 'mongodb://localhost:27017/test'; // change test to whichever db you added the collections to 

app.get('/partOfGroup', (req, res) => { 
    if (req.query.groupId == null || req.query.userId == null) { 
     return res.send('Must include both groupId and userId') 
    } else { 
     MongoClient.connect(url, function(err, db) { 
      var collection = db.collection('groups'); 
      collection.findOne({ 
       _id: ObjectID(req.query.groupId), 
       group_members: { 
        $elemMatch: { user_id: req.query.userId} 
       } 
      }, function(err, result) { 
       return res.send(result != null) 
      }) 
     }) 
    } 
}); 

app.listen(3000, function() { 
    console.log('Example app listening on port 3000'); 
}); 

隨着那運行起來,你可以去到url http://localhost:3000/partOfGroup?groupId=594ea5bc4be3b65eeb8705d8&userId=12345和它應該返回取決於是否有id爲594ea5bc4be3b65eeb8705d8和用戶ID爲12345一羣真或假在那個小組裏。

從您的前端代碼,當登錄用戶訪問組頁面時,請求該URL,適當地替換組ID和用戶ID。您得到的迴應將決定是否顯示「加入」或「離開」按鈕。

+0

謝謝,這看起來輝煌。不能等待明天嘗試。 – TheGabornator

相關問題