Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose query: find an object by id in an array

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
  }]
});
like image 627
user3888540 Avatar asked Nov 14 '16 20:11

user3888540


1 Answers

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} } );
like image 74
adebasi Avatar answered Oct 18 '22 19:10

adebasi