danielemm danielemm - 10 months ago 49
Node.js Question

Mongoose search for an object's value in referenced property (subdocument)

I've two schemas:

var ShelfSchema = new Schema({
tags: [{
type: Schema.Types.ObjectId,
ref: 'Tag'

var TagSchema = new Schema({
name: {
type: String,
unique: true,
required: true

I would to search for all Shelves where the tags array has a tag with a specific value.

I've tried using:

modelShelf.find({tags 'tags.name': 'mytag'})...

but it does not work. It always return an empty array.
Any idea?
Looking at db each Shelf instance links only the objectID of the tags.
I've used reference because I need to work also with Tag(s) entities.


In mongoDB you essentially can't do this directly as queries target a single collection at a time. Recently there were added new features which allow some kind of join when using the aggregation framework but for your needs that is not necessary.
From your schemas I see that the tags' names are unique so you can first fetch your desired tag with something like

modelTag.find({name: 'mytag'})

in order to get the tag's ID and then query your shelf collection for this tag ID

modelShelf.find({tags: tagId})