0
votes

Trying to query a subdocument array which contains ObjectId refs, and find one item.

The items are ObjectId's and get populated when I add a new lesson and 'assign' it to a specific location.

This mongoose schema shows what i mean.

var mongoose = require('mongoose');

var lessonNames = new mongoose.Schema({
  day: {type: String },
  name: {type: String},
  startTime: {type: String},
  endTime: {type: String}
});

var locationNames = new mongoose.Schema({
  name: {type: String, required: true},
  address: String,
  lessons: [ { type: mongoose.Schema.Types.ObjectId, ref: 'lessonnames'}]
});

mongoose.model('lessonnames', lessonNames);
mongoose.model('locationnames', locationNames);

I have added a lesson to one location, and now i'm trying to find this specific lesson. I've tried a couple of methods, but none worked for me. Every time i get a null or undefined reported when i output the query to the console.log.

      if (location.lessons && location.lessons.length > 0) {
        loc
            .findById(req.params.locationid)
            .populate('lessons', '_id')
              .exec(function (err, myLesson) {
                console.log(myLesson.lessons)
              });

When i execute the above statement, i see the following being generated in the nodejs console, with mongoose debugging enabled.

Mongoose: locationnames.findOne({ _id: ObjectId("56d4b687c4bcb5681a870cb5") }) { fields: undefined }  
GET /api/locations/56d4b687c4bcb5681a870cb5/lesson/56d4b687c4bcb5681a870cb4 
Mongoose: lessonnames.find({ _id: { '$in': [ ObjectId("56d4b687c4bcb5681a870cb4") ] } }) { fields: { _id: 1 } } 

The code line below is the output from console.log. As you can see, the ObjectId is shown as part of the lessons array. But how do I make a query which 'selects' this ObjectId, so i can reference with it to a lesson.

[{"_id":"56d4b687c4bcb5681a870cb4"}]

Search the web, and saw some posts about the _id nog being a string type, and i should cast it to be a string. But i think it should be possible with ObjectId and it should be rather easy to query for it, but i lack good knowledge of mongoose and mongodb to get it working.

Any help would be appreciated!

1

1 Answers

0
votes

Please try it as below, the {_id: "56d4b687c4bcb5681a870cb4"} in populate to match the ids in lessons array.

loc.findById(req.params.locationid)
   .populate('lessons', null, {_id: "56d4b687c4bcb5681a870cb4"})
   .exec(function (err, location) {

   });