【问题标题】:What is the best way to query data conditionally in MongoDB (node.js)?在 MongoDB(node.js)中有条件地查询数据的最佳方法是什么?
【发布时间】:2017-11-28 01:17:50
【问题描述】:

我基本上想要做的是根据用户是否是组的一部分在前端(react.js)上呈现不同的外观。我尝试了条件查询,在前端循环等。

你会采取什么方法来解决这个问题?

我最后一次尝试是聚合,但它没有返回任何值:

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

        }
   ]
            )

【问题讨论】:

  • “基于用户是否是组的一部分” - 你能详细说明这个条件,并包括你尝试过的一些代码吗?
  • 问题是无论我尝试什么都失败了。
  • 我想要的是例如Facebook。只要您不在组中,您就会看到一个加入按钮。进入后,您会看到离开按钮。简单的理论背后的过程是什么?
  • 你能提供一个你尝试过的至少一件事的例子吗?否则怎么会有人提出改进建议? This page 提供如何提出好问题的说明
  • 我添加了它。提前谢谢你。

标签: node.js mongodb reactjs


【解决方案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 如果有一个组具有该 _id 和一个 group_members 数组,其中包含一个具有指定用户 ID 的元素,否则为 0。

现在要在 Node 中使用它,您可以将 MongoDB NodeJS DriverExpress 网络服务器结合使用:

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,它应该返回 true 或 false,具体取决于该组中是否有 ID 为 594ea5bc4be3b65eeb8705d8 的组和 ID 为 12345 的用户。

当登录用户访问群组页面时,从您的前端代码向该 URL 发出请求,适当地替换群组 ID 和用户 ID。您得到的响应将决定是显示“加入”还是“离开”按钮。

【讨论】:

  • 谢谢,看起来很棒。迫不及待想明天试试。
猜你喜欢
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-19
  • 2015-10-09
  • 2013-02-28
  • 2012-04-01
  • 1970-01-01
相关资源
最近更新 更多