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'
    }
  }
};
在my
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(“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()
来加载所有相关关联