Javascript 如何使用Sails 0.10.x在一对多关系中引用关联模型
我正在使用Javascript 如何使用Sails 0.10.x在一对多关系中引用关联模型,javascript,node.js,mongodb,associations,sails.js,Javascript,Node.js,Mongodb,Associations,Sails.js,我正在使用Sails.js0.10.x版,我刚刚开始尝试它的associations功能 在我的场景中,我有一个拥有许多文档的用户 因此在/api/models/User.js中,我有: module.exports = { // snipped out bcrypt stuff etc attributes: { email: { type: 'string', unique: true, index: true, requir
Sails.js
0.10.x版,我刚刚开始尝试它的associations
功能
在我的场景中,我有一个拥有许多文档的用户
因此在/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'
},
}
};
module.exports = {
attributes: {
name: 'string',
owner: {
model: 'user'
}
}
};
在/api/models/Document.js
中,我有:
module.exports = {
// snipped out bcrypt stuff etc
attributes: {
email: {
type: 'string',
unique: true,
index: true,
required: true
},
documents: {
collection: 'document',
via: 'owner'
},
}
};
module.exports = {
attributes: {
name: 'string',
owner: {
model: 'user'
}
}
};
在myDocumentController
中,我有以下内容:
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(“xxxxxxxxxxxxxxxxxxxx”)
,这与预期一致
但是,当我稍后通过sails.log.debug检查DocumentController中的req.user
对象时(“用户拥有documts”,req.user.documents)代码>我明白了
debug: user has documents [ add: [Function: add], remove: [Function: remove] ]
而不是文档
对象的数组
在我生成的slim
模板中
if req.user.documents.length > 0
ul
for doc in req.user.documents
li= doc.toString()
else
p No Documents!
我总是得到“没有文件!”
我似乎遗漏了一些明显的东西,但我不确定那是什么。我通过涉水查看吃水线
源代码解决了这个问题
首先,正如我所希望的,关联的双方都受到文档
实例创建的影响,我只需要重新加载我的用户
在控制器中,这就像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);
});
}
现在,每个请求都正确加载了用户
及其关联
我不得不在源代码中查找populateAll()
方法,因为我在任何地方都找不到它的文档。我也可以使用populate('documents')
来代替,但我将向用户添加其他关联,因此需要populateAll()
来加载所有相关关联