Mongoose包含依赖关系的模型
我正在创build一个基于此示例的节点应用程序。
server.js
具有以下内容:
fs.readdirSync(__dirname + "/app/model").forEach(function (file) { if (~file.indexOf(".js")) { require (__dirname + "/app/model" + "/" + file); } });
这包括来自app/model
所有文件。 这有效,但问题是, 我的模型有引用依赖关系,在这个例子中没有出现。 具体来说,我有这样一个模型:
ResourceSchema = new Schema({ "comment": [Comment] });
但是,当我运行node
我得到一个错误, Comment
没有定义,这并不是真的意外。
这个例子中没有提到,即使模式有一个引用,因为它使用:
user: {type : Schema.ObjectId, ref : 'User'},
我的问题是,我应该使用"comment": {type: [Schema.ObjectId], ref: "Comment"}
而不是(或其他?)是否有一个正确的方法来包括在资源模式声明?
如果你想定义一个引用数组,你应该使用下面的定义:
ResourceSchema = new Schema({ "comment": [{type : Schema.ObjectId, ref : 'Comment'}] });
您定义注释的方式用于定义一个子文档数组( 请参阅mongoose API文档 )。
所以,只有当你想把所有的注释直接存储在父文档中时,你才应该使用它。 在这种情况下,应该已经定义了Comments
模式,或者需要使用其他模块。