[英]Mongoose how to query an array of subdocuments with an array?
I'm setting up a new server, using mongoDB for the DB and mongoose to interact with it. 我正在建立一个新服务器,将mongoDB用于数据库,并使用mongoose与之交互。 I have links of images saved in the DB with tags, all the images have the common tag:
*
(which get retrieved and saved when saving a new image) And I want to retrieve images with all the given tags. 我将带有标签的图像链接保存在数据库中,所有图像都具有通用标签:
*
(在保存新图像时会进行检索和保存),并且我想使用所有给定标签来检索图像。
Here is the schema for the images 这是图像的架构
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);
Here is the schema for the tags 这是标签的架构
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);
Here is what i have tried 这是我尝试过的
Image.find({
tags: {
$elemMatch: {
name: { $in: ['*'] }
}
}
}).populate('tags');
and also 并且
Image.find({
'tags.name': { $in: ['*'] }
}).populate('tags');
but I get no images. 但我没有图像。 But when I do a simple
Image.find().populate('tags');
但是当我做一个简单的
Image.find().populate('tags');
I do get all the images with the property tags that is an array of objects, with for only one object a tag with for name: *
. 我的确获得了所有带有属性标记的图像,这些属性标记是一组对象,只有一个对象具有名称为
*
的标记。
What did i do wrong? 我做错了什么?
if you're trying to find all the images that have the '*'
tag, perhaps you can try - 如果您要查找所有带有
'*'
标签的图片,则可以尝试-
find().
populate({
path: 'tags',
match: { name: '*' }
}).
exec();
This link will be useful to you I think - https://mongoosejs.com/docs/populate.html#query-conditions 我认为此链接对您很有用-https: //mongoosejs.com/docs/populate.html#query-conditions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.