如何引用与Sails 0.10.x的一对多关系的相关模型
我正在使用Sails.js
版本0.10.x,刚刚开始尝试它的associactions
东西。
在我的情况下,我有一个拥有多个文档的用户。
所以在/api/models/User.js
我有:
module.exports = { // snipped out bcrypt stuff etc attributes: { email: { type: 'string', unique: true, index: true, required: true }, documents: { collection: 'document', via: 'owner' }, } };
并在/api/models/Document.js
我有:
module.exports = { attributes: { name: 'string', owner: { model: 'user' } } };
在我的DocumentController
我有以下几点:
fileData = { name: file.name, owner: req.user } Document.create(fileData).exec(function(err, savedFile){ if (err) { next(err); } else { results.push({ id: savedFile.id, url: '/files/' + savedFile.name, document: savedFile }); next(); } });
通过命令行查看我的本地mongo
数据库,我可以看到文档的所有者字段设置如下"owner" : ObjectId("xxxxxxxxxxxxxxxxxxxxxxxx")
,如预期的那样。
但是,当我通过sails.log.debug("user has documemts", req.user.documents);
检查了DocumentController中的req.user
对象时sails.log.debug("user has documemts", req.user.documents);
我懂了
debug: user has documents [ add: [Function: add], remove: [Function: remove] ]
而不是一个Document
对象的数组。
在我最终的slim
模板
if req.user.documents.length > 0 ul for doc in req.user.documents li= doc.toString() else p No Documents!
我总是得到“没有文件!”
我似乎错过了一些明显的东西,但我不确定那是什么。
我通过阅读Waterline
源代码来解决这个问题。
首先,正如我所希望的那样,协会的双方都受到创buildDocument
实例的影响,我只需要重新加载我的用户。
在控制器中,这就像User.findOne(req.user.id).populateAll().exec(...)
我也修改我的passport
服务帮手如下
function findById(id, fn) { User.findOne(id).populateAll().exec(function (err, user) { if (err) return fn(null, null); return fn(null, user); }); } function findByEmail(email, fn) { User.findOne({email: email}).populateAll().exec(function (err, user) { if (err) return fn(null, null); return fn(null, user); }); }
现在,每个请求都可以正确加载user
及其关联。
我不得不挖掘源代码findpopulateAll()
方法,因为它实际上没有logging在任何我能find的地方。 我也可以使用populate('documents')
但我要添加其他关联到用户,所以需要populateAll()
加载所有相关的关联。
- 水线
associations
文件 - 水线
/lib/waterline/query/deferred.js#populateAll