Sulaiman
Sulaiman

Reputation: 61

Mongoose: How to find by 2 fields where one field exists in document and other in sub-documents?

Below is my schema.

var prayerSchema = new Schema({
    totalSteps:{
      type: Number
    },
    name: String,
    steps: [{type: Schema.Types.ObjectId, ref:'Step'}]
});


var stepSchema = new Schema({
    stepNumber : {
       type: Number
    },
    _prayer : {
         type: Schema.Types.ObjectId, ref: 'Prayer', required: true
    } 
 });

Each prayer will have totalsteps, name and steps.
Each steps will have stepNumber and prayerModel associated with it.
Step document will look like this:

{
   "stepNumber":1,
   _prayer:[
       "name":"prayer1",
       "totalSteps":5,
       "steps":[]
    ] 
 },
 {
    "stepNumber":2,
    _prayer:[
        "name":"prayer2",
        "totalSteps":10,
        "steps":[]
     ]   
  }

I am trying to query by name exists in sub-document(_prayer) of stepSchema and stepNumber of stepSchema.

Step.find({_prayer :{ name: req.query.name} }, {stepNumber: 1});
Step.find({'_prayer.name' : req.query.name, stepNumber: 1});

Both these above codes didnot work. One way I found is to query Prayer document first by its name and get its _id and query again Step document by the found _id and stepNumber.

Prayer.findOne({name:"name"})
   .exec((err, prayers) => {

    Rakah.find({ _prayer: prayers._id, stepNumber: stepNumber })

    ....
});

But this approach will become difficult for nested documents. Are there any ways to query by one document only to get the result ?

Upvotes: 0

Views: 823

Answers (1)

mickl
mickl

Reputation: 49945

Both filtering conditions should be included in one object of find like this:

Step.find({'_prayer.name' : req.query.name, stepNumber: 1 })

Second parameter represents projection part so you were simply getting only _id and stepNumber (1 means that field should be included in results)

Upvotes: 1

Related Questions