【问题标题】:How to reference associated models in a one-to-many relationship with Sails 0.10.x如何使用 Sails 0.10.x 以一对多关系引用关联模型
【发布时间】:2014-07-04 10:03:34
【问题描述】:

我正在使用 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 对象时,我看到了

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!

我总是得到“没有文件!”

我似乎遗漏了一些明显的东西,但我不确定那是什么。

【问题讨论】:

    标签: javascript node.js mongodb associations sails.js


    【解决方案1】:

    我通过浏览Waterline 源代码解决了这个问题。

    首先,正如我所希望的,关联的双方都会受到Document 实例的创建影响,我只需要重新加载我的用户。

    在控制器中,这就像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 及其关联已根据请求正确加载。

    我不得不挖掘源代码以找到 populateAll() 方法,因为它实际上并没有在我能找到的任何地方记录。我也可以改用populate('documents'),但我即将向用户添加其他关联,因此需要populateAll() 来加载所有相关关联。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-10
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 2014-10-03
      相关资源
      最近更新 更多