node.js 使用 Mongoose (MongoDB) 查询嵌套文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13097266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Querying nested documents using Mongoose (MongoDB)
提问by Vlad
I am starting out with mongodb and having hard time trying to query nested documents. I have two schemas:
我开始使用 mongodb 并且很难尝试查询嵌套文档。我有两个模式:
var LinkSchema = new mongoose.Schema({
url: String,
name: String
});
var UserSchema = new mongoose.Schema({
name: String,
links: [LinkSchema]
});
As you can see, I am just tying to build a simple bookmarking tool. Each user has a name and a collection of links. Each link has a name and a url.
如您所见,我只是想构建一个简单的书签工具。每个用户都有一个名称和一组链接。每个链接都有一个名称和一个 url。
Now, what I am trying to do is for example, see if a link already exists in someone's links array. I would like to be able to do something like this (Trying to get vlad's link collection and then see if the query link already belongs to the collection or not):
现在,我想做的是,例如,查看某人的链接数组中是否已存在链接。我希望能够做这样的事情(尝试获取 vlad 的链接集合,然后查看查询链接是否已经属于该集合):
app.get("/:query", function(req, res){
User.findOne({"name":"vlad"}, function(err, user){
user.links.find({"url":req.params.query}, function(err, foundLinks){
if(foundLinks){
res.send("link already exists!");
} else {
res.send("link doesn't exist!");
}
});
});
});
Of course, this code doesn't work, because apparently I can't do a "user.links.find()". I guess I can just do a user.links.map to extract only urls and then run a membership query against it. But I think this would be far from the right solution. There's gotta be a way to do something like this natively using DB queries. Can someone help? Thank you!
当然,这段代码不起作用,因为显然我不能做“user.links.find()”。我想我可以做一个 user.links.map 来只提取 url,然后对其运行成员资格查询。但我认为这远非正确的解决方案。必须有一种方法可以使用 DB 查询在本机上执行此类操作。有人可以帮忙吗?谢谢!
回答by RameshVel
You can query an embedded document in mongoose like this
您可以像这样在 mongoose 中查询嵌入的文档
User.find({'links.url':req.params.query}, function(err, foundUsers){
// ---
});
and to find the links that belong to the user "vlad", you can write
并找到属于用户“vlad”的链接,你可以写
User.find({name:'vlad','links.url':req.params.query}, function(err, foundUsers){
// ---
});
This will do the trick.
这将解决问题。
回答by Sritam
To find a specific link that belongs to a specific user you can do this
要查找属于特定用户的特定链接,您可以执行此操作
User.find({name:'vlad','links.url':req.params.query}, { 'links.$': 1 }, function(err, foundUsers){
// ---
});

