0

Now I'm doing it like so

Client.findOne({_id: client_id}, function (err, client) {

        if(err){ return next() }

        var phone = client.phones.filter(function (phone) {
             return phone._id === phone_id;
        }).pop();

        res.status(200).send(phone);
});

,but not sure if that the right way of doing it. My schema is like this

{
    "_id" : ObjectId("560b05b6fd9d267f60b7bb28"),
    "email" : "email@email.com",
    "__v" : 1,
    "phones" : [
        {
            "_id" : ObjectId("561a22cbe6ebf6d62965b4bc"),
            "phone" : "1234"
        }
    ]
}

So I would like to get phone 1234 by 560b05b6fd9d267f60b7bb28 and 561a22cbe6ebf6d62965b4bc

Cœur
  • 37,241
  • 25
  • 195
  • 267
Alex
  • 579
  • 5
  • 24

1 Answers1

1

A subdocument can't have an _id, at least not with the same semantics. A document's _id is always indexed and has to be unique and has some other implications. The _id field in the phones array of your documents is a normal field as phone.

So you can access it the usual way. In shell terms:

var doc = db.phones.findOne(
  // query part
  {
    "_id": knownIdOfDocument,
    "phones": $elemMatch:{"_id": knownIdOfSubdocument}
  },
  // projection
  { "phones.$":1 }
)
var phone = doc['phones'][0]; // Iirc, my JS is a bit rusty.
Markus W Mahlberg
  • 19,711
  • 6
  • 65
  • 89