'How to Filter mongoose data if array of element is include in array of object key value from two different model schema?

I have to Filter out data in mongoose where Schema one is user schema and another is task schema. Here is how my user schema looks like: User Schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  ...
  Skills: [
    {
      skillId: { type: Schema.Types.ObjectId, required: true, ref: 'category' },
      level: { type: String, required: false },
      description: { type: String }
    }
  ],
  ...
});

module.exports = User = mongoose.model('User', UserSchema);

And Here another Schema: Task Schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const TaskSchema = new mongoose.Schema({
  ...
  skillRequired: [
    {
      type: Schema.Types.ObjectId,
      ref: 'category'
    }
  ],
  ...
});

module.exports = Task = mongoose.model('Task',TaskSchema);

Now I want to filter out task based on user skills. If user have skills like

Skills: [{
skillId: '123',
level: 'beginner',
description: ''
},{
skillId: '321',
level: 'expert',
description: ''
}]

and i have list of task in my collection as:

[{
taskId: 'task1',
skillRequired: [123, 321]
},
{
taskId: 'task2',
skillRequired: [456]},
{
taskId: 'task3',
skillRequired: [321]}
]

Then the expected result should be: Expected Result

[{
taskId: 'task1',
skillRequired: [123, 321]
},
{
taskId: 'task3',
skillRequired: [321]
}
]

I would really appreciate help from community. Thank you in advance :)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source