node.js - Mongoose subdocument meet multiple conditions simultaneously -


i have schema set resource, skill, , resourceskilllevel. first 2 names, , latter has reference resource, skill, , level. select resources match skill levels simultaneously.


schema

// omitting fields don't matter purpose of question resourceschema = new schema({name: string}); skillschema = new schema({name: string}); resourceskilllevelschema = new schema({                                              "resource": {type: schema.objectid, ref: "resource"},                            "skill": {type: schema.objectid, ref: "skill"},                                  "level": {type: number, min: 1, max: 5}                                      }); 

problem

currently have:

resourceskilllevel.find({$and: [     {skill: "node.js", level: {$gte: 3}},     {skill: "mongodb", level: {$gte: 3}}, ]}) 

this return resourceskilllevel entries, there 2 problems:

  • this condition impossible since 1 resourceskilllevel entry cannot meet both conditions simultaneously
  • i want resource entries satisfy of these conditions. if got resourceskilllevel entries resource them, i'm sure there simpler way.

requirement

in case don't understand, need way resource entries match required resourceskilllevel entries simultaneously. is, based on query above should able resource has 4 in node.js and mongodb, not resource has 2 in node.js or not have skill level either of skills @ all.

my way of implementing change schemas follows:

skillschema = new schema({name: string, level: {type: number, min: 1, max: 5}}); resourceschema = new schema({name: string, skills: [skillschema]}); 

i forget if mongoose allows embedding schemas this...

then can query so:

resource.find({skills: [{"name": "nodejs", "level": 2},{"name": "mongodb", "level": 3}]}) 

this should of way getting right.


edit show better way this.

you store skills in own collection , store array of skills in resource schema following fields:

skillschema = new schema({name: string }); resourceschema = new schema({name: string, skills: [{skill_id: string, level: {type: number, min: 1, max: 5}}]}); 

this way can have single collection of skills , reference _id of skill in skills collection on resource.

your query looks like:

resource.find({skills: [{"skill_id": skill id skillschema collection, "level": 2},{"skill_id": skill id skillschema collection, "level": 3}]}) 

this should work you


Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

php - MySQLi multi_query results for later use -