Reputation: 191749
I'm creating a node application based off of This example.
server.js
has the following:
fs.readdirSync(__dirname + "/app/model").forEach(function (file) {
if (~file.indexOf(".js")) {
require (__dirname + "/app/model" + "/" + file);
}
});
This includes all of the files from app/model
. This works, but the problem is that my models have reference dependencies that don't come up in the example. Specifically I have a model like this:
ResourceSchema = new Schema({
"comment": [Comment]
});
However when I run node
I get an error that Comment
is not defined, which is not really unexpected.
This does not come up in the example even though the schema has a reference because it uses:
user: {type : Schema.ObjectId, ref : 'User'},
My question is, should I use "comment": {type: [Schema.ObjectId], ref: "Comment"}
instead (or something else?) Is there a proper way to include the schema reference for Comment in the Resource Schema declaration?
Upvotes: 2
Views: 2103
Reputation: 51470
If you want to define an array of references, you should use the following definition:
ResourceSchema = new Schema({
"comment": [{type : Schema.ObjectId, ref : 'Comment'}]
});
The way you defined comments is used to define an array of subdocuments (see mongoose API docs).
So, you should use it only if you want to store all your comments directly inside of the parent document. In this case Comments
schema should be already defined, or required from another module.
Upvotes: 3