Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

@alexdeefuse
Copy link

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!

@aheckmann
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants