mongoose query: find an object by id in an array

user3888540 picture user3888540 · Nov 14, 2016 · Viewed 13.5k times · Source

How could I find an image by id in this Schema. I have the id of the User and the id of the image I am looking for. What would be the best way to do this and do all images in this case have different ids or could they have the same id because they don't belong to the same User?

My Schema looks like this:

var userSchema = new Schema({
  local: {
    email: String,
    password: String
  },
  facebook: {
    id: String,
    token: String,
    email: String,
    name: String
  },
  name: String,
  about: String,
  images: [{
    id: Schema.ObjectId,
    link: String,
    main: Boolean
  }]
});

Answer

adebasi picture adebasi · Nov 14, 2016

When you are interested in the full object it is a simple find:

.find({"facebook.id":"<id>", "images.id":<image-id>})

I don't think that there is a way to reduce the image array in the result.

To update a single element in the image array you can use this:

.update({"facebook.id":"<id>", "images.id":<image-id>}, {$set : {"images.$.main" :false} } );