Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying nested documents using Mongoose (MongoDB)

I am starting out with mongodb and having hard time trying to query nested documents. 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):

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!

like image 392
Vlad Avatar asked Oct 27 '12 04:10

Vlad


People also ask

How do I query a nested document in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.

What is $in in Mongoose?

The value of the $in operator is an array that contains few values. The document will be matched where the value of the breed field matches any one of the values inside the array.


1 Answers

You can query an embedded document in mongoose like this

   User.find({'links.url':req.params.query}, function(err, foundUsers){       // ---    }); 

and to find the links that belong to the user "vlad", you can write

   User.find({name:'vlad','links.url':req.params.query}, function(err, foundUsers){       // ---    }); 

This will do the trick.

like image 194
RameshVel Avatar answered Sep 29 '22 09:09

RameshVel