Schema definition order is important for document array .id() method and find nested doc using string id #622

Closed
alexdeefuse opened this Issue Nov 23, 2011 · 1 comment

Comments

Projects
None yet
2 participants

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!

Collaborator

aheckmann commented Nov 23, 2011

you are absolutely correct, order matters when declaring a schema. Since Task was still undefined, the tasks property was interpreted as [] which is an array of Mixed types. This means no casting takes place b/c there isn't a subdocument schema. Also, since its not a subdoc schema you don't get the DocumentArray type and instead just get generic Array type without the id() method.

Glad you figured it out.

aheckmann closed this Nov 23, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment