MongoDB query on multiple array of objects
The query object should look like this for your example
{ $or: [ { original: { name: "English", code: "en" }, target: { $in: [{ name: "Japanese", code: "jp" }, { name: "Chinese", code: "cn" }] } }, { original: { name: "Korean", code: "ko" }, target: { $in: [{ name: "Japanese", code: "jp" }, { name: "English", code: "en" }] } } ]}
So you will have to construct the condition from prefLang
like this
const query = { $or: perfLang.map(lang => ({ original: lang.main, target: { $in: lang.secondary } }))}const post = await Post.find(query)
Tip:
If the language objects have a strict schema, you can define them like this
const LanguageSchema = new mongoose.Schema({ name: String, code: String}, { _id: false})const UserSchema = new mongoose.Schema({ //... googleId: String, name: String, Language: [{ main: LanguageSchema, secondary: [LanguageSchema] }]})
Sounds like the usage of basic boolean logic would suffice:
const prefLang = req.user.Language;let conditions = [];prefLang.forEach((langObj) => { let tragetLangs = langObj.secondary.map(lang => lang.code); conditions.push({ $and: [ { "original.code": langObj.main.code, }, { "target.code": {$in: tragetLangs} } ] })})// you should check conditions !== empty array.const post = await Post.find({$or: conditions})