[英]How can I access a specific attribute of a specific document in a mongoDB collection?
To summarize, I am working with 2 collections - 'usercollection' and 'groupcollection' and I would like to associate users with groups.总而言之,我正在使用 2 collections -“usercollection”和“groupcollection”,我想将用户与组相关联。 I don't want to have 2 copies of all the user documents so I have a unique ID attribute for each user that I want to use to associate specific users with specific groups.
我不想拥有所有用户文档的 2 个副本,因此我对每个用户都有一个唯一的 ID 属性,我想用它来将特定用户与特定组相关联。 This is all running on a localhost webserver so I'm getting the input from an html page with a form in it where you enter 'username' and 'groupname'.
这一切都在本地主机网络服务器上运行,所以我从 html 页面获取输入,其中包含输入“用户名”和“组名”的表单。 I tried using the.distinct() function with query as 'username' and the target field/attribute as 'uid'.
我尝试使用.distinct() function,查询为“用户名”,目标字段/属性为“uid”。
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
// Set query and options for searching usercollection
var query = {"username" : userName};
const fieldName = "uid";
// Set our collections
var users = db.get('usercollection');
// Get UID corresponding to username
var uidToAdd = users.distinct(fieldName, query);
This is what I attempted (with some other lines that aren't relevant taken out) but it just returned a null object so I'm at a bit of a loss.这是我尝试的(删除了一些其他不相关的行),但它只返回了 null object 所以我有点不知所措。 Also, I'm still a beginner with nodejs/javascript/mongoDB so the more informative the answer the better!
另外,我仍然是 nodejs/javascript/mongoDB 的初学者,所以答案越丰富越好! When I do the same code in the mongo shell I can get the actual value of the 'uid' attribute so I really don't know what's going wrong
当我在 mongo shell 中执行相同的代码时,我可以获得“uid”属性的实际值,所以我真的不知道出了什么问题
I am not sure I am following you.我不确定我是否在关注你。 But if I understood correctly, if you want to make a relationship between ' usercollection ' and ' groupcolletion ', you can simply create those 2 collections and each user in ' usercollection ' should have a field with ' groupid ' as a reference.
但是如果我理解正确,如果你想在' usercollection '和' groupcolletion '之间建立关系,你可以简单地创建这2个collections,' usercollection '中的每个用户都应该有一个带有' groupid '的字段作为参考。 In this way, you can access ' groupcollection ' easily.
这样,您可以轻松访问“ groupcollection ”。
Here is an example with using mongoose.这是使用 mongoose 的示例。
In User model在用户model
...
groupId: {
type: mongoose.Schema.Types.ObjectID
ref: "Group"
}
...
Later you can also use ' populate ' to fetch ' Group ' information.稍后您还可以使用“填充”来获取“组”信息。
...
let data = await User.findById(id).populate('groupId');
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.