mongoose query: find an object by id in an array

2020-06-04 09:40发布

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
  }]
});

2条回答
闹够了就滚
2楼-- · 2020-06-04 09:45
userSchema .find({facebook.id: "some ID",{ "images.id": { $in: [ id1, id2, ...idn] }}

since images are inside the document you can have same ID's however every time you query you should keep in mind that you send some other parameters such as facebook.id or facebook.email along with image id's to retrieve them. Otherwise you end up getting all that might be irrelevant only because you decide to keep same ID's for images.

查看更多
smile是对你的礼貌
3楼-- · 2020-06-04 10:10

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} } );
查看更多
登录 后发表回答