Colin
Colin

Reputation: 1855

MongooseJS Query select attributes of subdocument

Given a model foo with the following schema;

{
    a: String,
    b: [{c: String, d: String}]
}

Assume the values of a are unique, and assume the values of c in a given foo document are unique. If I had values A and C of a and c respectively, then A uniquely identifies a foo document, and C uniquely identifies a foo.b sub-document. Is it possible then, to forge a query that returns to me the value of d?

Conceptually,

foo ----(find({a:A}))-----> foo_document -----(find({c:C}))------>foo_subdoc-------(select(d))---->value_of_d

Enough information is given, I just don't know if Mongoose has a a mechanism for this.

Upvotes: 0

Views: 164

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You can use the $elemMatch projection operator to identity the matching b element to include:

foo.find({a: A}, {b: {$elemMatch: {c: C}}}, function(err, doc) {
    // doc.b[0].d contains the value of d you're looking for.
});

Upvotes: 1

Related Questions