Jaseem Abbas
Jaseem Abbas

Reputation: 5230

Waterline : Access populated value within a model

I am using sails.js to develop my first app. I have a waterline model as shown below.

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

        //more attributes

        userId: {
            model: 'user'
        },

        //more attributes
    }
};

I am using the model in one of my controllers as shown below.

  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

                });

How do I get access to the populated value inside the model?

Upvotes: 1

Views: 205

Answers (2)

taufique
taufique

Reputation: 2751

It's because find return an array of records. You have to use index to access an object and then userId of that object.

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

Upvotes: 1

Muntasim
Muntasim

Reputation: 6786

ModelA.find returns array of items.

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

        });

Or you can use ModelA.findOne for a single record

Upvotes: 1

Related Questions