猫鼬查询:按ID在数组中查找对象 [英] mongoose query: find an object by id in an array

查看:93
本文介绍了猫鼬查询:按ID在数组中查找对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在此架构中按ID查找图像.我有用户ID和要查找的图像ID.最好的方法是什么?在这种情况下,所有图像都具有不同的ID?或者由于它们不属于同一用户,它们是否可能具有相同的ID?

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?

我的模式如下:

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

推荐答案

当您对整个对象感兴趣时,它是一个简单的find:

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

这篇关于猫鼬查询:按ID在数组中查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆