MongoDB, Mongoose: How to find subdocument in found document?

mongodb, mongoose

Solution

You need to either create a NEW Schema for your embedded documents, or leave the type declaration as a blank array so `mongoose` interprets as a `Mixed` type.

var userSchema = new mongoose.Schema({
  name: String,
  photos: []
});
var User = mongoose.model('User', userSchema);

-- OR --

var userSchema = new mongoose.Schema({
  name: String,
  photos: [photoSchema]
});

var photoSchema = new mongoose.Schema({
  src: String,
  title: String
});

var User = mongoose.model('User', userSchema);

And then you can save thusly:

var user = new User({
  name: 'Bob',
  photos: [ { src: '/path/to/photo.png' }, { src: '/path/to/other/photo.png' } ]
});

user.save();

From here, you can simply use array primitives to find your embedded docs:

User.findOne({name: 'Bob'}, function (err, user) {

  var photo = user.photos.filter(function (photo) {
    return photo.title === 'My awesome photo';
  }).pop();

  console.log(photo); //logs { src: '/path/to/photo.png', title: 'My awesome photo' }
});

-- OR --

You can use the special `id()` method in embedded docs to look up by id:

User.findOne({name: 'Bob'}, function (err, user) {
    user.photos.id(photo._id);
});

You can read more here: http://mongoosejs.com/docs/subdocs.html

Make sure you DON'T register the schema with mongoose, otherwise it will create a new collection. Also keep in mind that if the child documents are searched for often, it would be a good idea to use refs and population like below. Even though it hits the DB twice, its much faster because of indexing. Also, `mongoose` will bonk on double nesting docs (i.e. The children have children docs as well)

var user = mongoose.Schema({
  name: String,
  photos: [{ type: Schema.Types.ObjectId, ref: 'Photo' }]
});

var photo = mongoose.Schema({
  src: String,
  title: String
});

User
  .findOne({ name: 'foo' })
  .populate('photos')
  .exec(function (err, user) {
    console.log(user.photos[0].src);
  });

Relevant docs can be found here http://mongoosejs.com/docs/populate.html

Problem

I'm stuck on trying to get subdocument by `_id` in found document. Example Schema ``` var User = mongoose.Schema({ name: String, photos: [{src: String, title: String}] }); var Team = db.model('Team', Team); ``` Now I'm getting one user: ``` myUser = User.findOne(...)... ``` How can I get now `src` of his photo by it's `_id` (or `title`)? Something like: ``` myUser.photos.findOne({'_id': myId}) ```

Original source