在MongoDB中查询集合;但是需要访问Schema对象上的不同属性

在MongoDB中查询集合;但是需要访问Schema对象上的不同属性,mongodb,mongodb-query,Mongodb,Mongodb Query,正在尝试找出如何在MongoDB中完成此查询: 分类模式 const CategorySchema = new Schema({ // Declare a unique name for each category. name: { required: true, type: String, unique: true }, // This is the object that contains the 3 responsive image collections. p

正在尝试找出如何在MongoDB中完成此查询:

分类模式

const CategorySchema = new Schema({
// Declare a unique name for each category.
  name: {
   required: true,
   type: String,
   unique: true
  },
// This is the object that contains the 3 responsive image collections.
 photos: {
   mobile: [],
   tablet: [],
   desktop: []
 }
});
附加照片

/**
* addPhoto(arg, arg2, arg3)
* - @param {String} name
* - @param {Object} image
* - @param {String} type
* - @return {Promise}
* - NOTE: Schema.statics allows for creating methods
* - on the Schema class.
*/
CategorySchema.statics.addPhoto = async function (name, image, type) {
  // Find category 'name' & push the imageUrl to the key 'photos' array.
  const list = await this.findOneAndUpdate({ name }, { $push: { photos: image.url } });
  // Return the updated category.
  return list;
  };
在将照片更改为包含3个数组的对象之前,最初addPhoto工作正常。现在我有一个addPhoto接受第三个参数类型,它将是photos对象中的3个键之一


我遇到的问题是如何提取这个查询。我按名称查询集合,因为它对每个集合都是唯一的。每个收藏中都有照片,所以我无法查询;但最终需要能够访问照片[type]才能执行$push。关于我如何才能做到这一点,有什么想法吗?我一直在使用一些不同的查询运算符,但都没有用。

您需要更新addPhoto函数,如

/**
* addPhoto(arg, arg2, arg3)
* - @param {Object} filter Eg {name: someName, type: someType}
* - @param {Object} image
* - @return {Promise}
* - NOTE: Schema.statics allows for creating methods
* - on the Schema class.
*/
CategorySchema.statics.addPhoto = async function (filter, image) {
  // Find category 'name' & push the imageUrl to the key 'photos' array.
  const list = await this.findOneAndUpdate(filter, { $push: { photos: image.url } });
  // Return the updated category.
  return list;
  };
从此以后,您可以添加更多过滤器