【问题标题】:Sails.js/Waterline populate deep nested associationSails.js/Waterline 填充深层嵌套关联
【发布时间】:2014-12-19 13:43:36
【问题描述】:

我知道 Sails.js/Waterline 中还没有内置的方式来填充深层嵌套关联,所以我尝试使用 bluebird 承诺来实现这一点,但我遇到了问题。

我成功检索了用户,以及与之关联的所有帖子(填充了图像集合)(console.log 显示所有内容都已正确填写)。但是,当我覆盖用户的属性“post”并尝试分配之前检索到的完全填充的帖子时,它没有正确填充 Post.js 的 images 属性。就像是ORM阻止了Post.js的图像集合被手动分配。

我做错了什么?填充深层嵌套的一对多关联的最佳方法是什么?

下面我已经粘贴了我正在执行的所有代码......

// Populate nested association
nested: function (req, res, next){
var username = req.param("id");

User
.findOneByUsername(username)
.populateAll()      
.then(function (user){
    var posts = Post.find({
        "user": user.id
    })
    .populate('images')
    .populate('category')
    .then(function (posts){
        return posts;
    });
    return [user, posts];
})
.spread(function (user, posts){
    user.posts = posts; // This won't work.... It assigns all the fields properly but the images collection attribute
    res.json(user);
}).catch(function (err){
    if (err) return res.serverError(err);
});
}

// --- User.js Model --- //
module.exports = {
   attributes: {
    .....,
    posts: {
        collection: "post",
        via: "user"
    },
    .....
   }
 }

// --- Post.js Model --- //
module.exports = {
    attributes: {
       ....,
       user: {
         model: "user"
       },
       images: {
         collection: "postImage",
         via: "post"
       },
       ....
    }
}

// --- PostImage.js Model --- //
module.exports = {

   attributes: {
     ....,
     post: {
       model: "post"
     }
   },
}

问候,

萨维奥·卢塞纳

【问题讨论】:

    标签: javascript sails.js waterline


    【解决方案1】:

    这可能是一个老问题,但最好有答案,所以sails.js 用户可以从中受益。

    您的问题是,当sails 返回一条记录(在数组内)时,该记录对应于关联的键实际上是getters/setters,似乎setter 确实不允许你想要什么。您可以使用Object.getOwnPropertyDescriptor(user, 'posts') 进行确认。 因此,为了能够根据需要覆盖该属性,您需要做的是在其上调用.toObject,(或通过_.clone 克隆其属性或手动循环但您会得到很多垃圾它,所以坚持.toObject),无论如何你都会得到一个具有你需要的属性的新对象,现在你如何修改它没有任何限制。

    所以您的代码将如下所示:

    User
    .findOneByUsername(username)
    .populateAll()      
    .then(function (user){
        var posts = Post.find({
            "user": user.id
        })
        .populate('images')
        .populate('category')
        .then(function (posts){
            return posts;
        });
        return [user, posts];
    })
    .spread(function (user, posts){
        user = user.toObject() // <- HERE IS THE CHANGE!
        user.posts = posts; // It will work now
        res.json(user);
    }).catch(function (err){
        if (err) return res.serverError(err);
    });
    }
    

    【讨论】:

      【解决方案2】:

      您必须覆盖 user.posts 数组中的每个帖子 ID 对象。有关更多信息,请查看此答案https://stackoverflow.com/a/26452990/4261327

      【讨论】:

      • Jani,你能在你的答案中进一步挖掘吗?我尝试了各种覆盖,但不知何故,因为图像是多对多关联,它阻止了特定字段被覆盖。
      猜你喜欢
      • 2014-06-20
      • 1970-01-01
      • 2016-03-01
      • 2014-10-24
      • 1970-01-01
      • 1970-01-01
      • 2015-02-09
      • 1970-01-01
      相关资源
      最近更新 更多