要拿出一个有效的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 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。您得到的回应将决定是否显示“加入”或“离开”按钮。
“基于用户是否是该组与否的一部分” - 你可以详细说说条件,并包括一些代码,你试过? –
问题是,无论我尝试失败。 – TheGabornator
我想要的是像例如Facebook的。只要你不在一个组中,你就会看到一个连接按钮。一旦你进入,你会看到离开按钮。简单理论背后的过程是什么? – TheGabornator