2017-06-24 56 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

相关问题