简体   繁体   English

使用Mongoose(MongoDB)查询嵌套文档

[英]Querying nested documents using Mongoose (MongoDB)

I am starting out with mongodb and having hard time trying to query nested documents. 我开始使用mongodb并且很难尝试查询嵌套文档。 I have two schemas: 我有两个架构:

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. 每个链接都有一个名称和一个网址。

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()". 当然,这段代码不起作用,因为显然我不能做“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. 我想我可以只做一个user.links.map来提取网址,然后针对它运行会员资格查询。 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! 谢谢!

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. 这样就可以了。

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){
      // ---
   });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM