LearnBoost/mongoose — Issue #622: Schema definition order is important for document array .id() method and find nested doc using string id
Author: alexdeefuse
Created: 2011-11-23 09:45:32+00:00
State: open

For some days now i've been working on a test project with mongoose.
The schema I originally used was:

var List = new Schema({
name	: String,
tasks	: [ Task ]
})

var Task = new Schema({
done	: {type: Boolean},
description	: {type: String}
});

Then inside one of my controllers i've tried the "find nested doc using string id" test method of returning the task that belonged to a list. The issue was that just by using a string it didn't work. I had to use instantiate a new ObjectId with the string in order to get the result.

var task_id = req.params.task.toString();
List.findOne( {'tasks._id': new ObjectId(task_id)}, function(err, list){

Another point is that when using the schema above, the .id(task_id) method for the "tasks" document array is undefined.

This lead me to using the exact schema definition from the documentation. Declaring the Task model before the List model made the .id(task_id) to be defined and point to a function and then the "find nested doc using string id" also worked.

I really don't know if this is really a bug but it seems that the order in which you declare the models is really important!