繁体   English   中英

猫鼬如何用数组查询子文档数组?

[英]Mongoose how to query an array of subdocuments with an array?

我正在建立一个新服务器,将mongoDB用于数据库,并使用mongoose与之交互。 我将带有标签的图像链接保存在数据库中,所有图像都具有通用标签: * (在保存新图像时会进行检索和保存),并且我想使用所有给定标签来检索图像。

这是图像的架构

const mongoose = require('mongoose');

const imageSchema = mongoose.Schema({
  link: {
    type: String,
    required: true
  },
  tags: {
    type: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Tag'
    ]},
    default: []
  }
});

consy Image = mongoose.model('Image', imageSchema);

这是标签的架构

const mongoose = require('mongoose');

const tagSchema = mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    maxlength: 20,
    lowercase: true
  }
});

const Tag = mongoose.model('Tag', tagSchema);

这是我尝试过的

Image.find({
  tags: {
    $elemMatch: {
      name: { $in: ['*'] }
    }
  }
}).populate('tags');

并且

Image.find({
  'tags.name': { $in: ['*'] }
}).populate('tags');

但我没有图像。 但是当我做一个简单的Image.find().populate('tags'); 我的确获得了所有带有属性标记的图像,这些属性标记是一组对象,只有一个对象具有名称为*的标记。

我做错了什么?

要查找常见标签,我们可以使用$ regex 请找到以下查询以检索所有带有*标签

Image.find({
  'tags.name': { $regex: /\*/, $options: 'i' } 
})

如果您要查找所有带有'*'标签的图片,则可以尝试-

find().
populate({
  path: 'tags',
  match: { name: '*' }
}).
exec();

我认为此链接对您很有用-https: //mongoosejs.com/docs/populate.html#query-conditions

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM