简体   繁体   中英

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. 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'); 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?

To find the common tags we can use the $regex . Please find the below query to retrieve all tags with *

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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