【问题标题】:Waterline : Access populated value within a modelWaterline:访问模型中的填充值
【发布时间】:2015-08-05 20:49:35
【问题描述】:

我正在使用sails.js 开发我的第一个应用程序。我有一个waterline 模型,如下所示。

//ModelA.js
module.exports = {
    attributes: {

        //more attributes

        userId: {
            model: 'user'
        },

        //more attributes
    }
};

我正在我的一个控制器中使用该模型,如下所示。

  ModelA.find(options)
                .populate('userId')
                .exec(function (err, modelA) {
                    //some logic
                    //modelA.userId is undefined here
                    res.json(modelA); //userId is populated in the JSON output

                });

如何访问模型中的填充值?

【问题讨论】:

    标签: node.js orm sails.js waterline


    【解决方案1】:

    ModelA.find 返回项目数组。

           ModelA.find(options)
            .populate('userId')
            .exec(function (err, results) {
                console.log(results[0].userId) //results is an array.
                //res.json(modelA); 
    
            });
    

    或者您可以将ModelA.findOne 用于单个记录

    【讨论】:

    • 只有在一对一关联时才有效。就我而言,这是一个一对多的关联。
    • 如果它是一对多的,为什么这不起作用?我看不出它有任何不工作的原因。
    【解决方案2】:

    这是因为 find 返回一个记录数组。您必须使用 index 来访问一个对象,然后是该对象的 userId。

    ModelA.find(options).populate('userId').exec(function (err, recordsOfModelA) {
        if(err) console.log(err);
        else console.log(recordsOfModelA[0].userId)
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 2016-04-18
      • 2017-03-23
      • 1970-01-01
      • 2019-02-28
      相关资源
      最近更新 更多