Reza SENTAX
Reza SENTAX

Reputation: 53

sails js mongodb populate

I would like to use .populate() with Sails js and MongoDB and so I did something like this:

I am using the latest version of Sails and MongoDB and Node.

My models look like:

// User.js
module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    pets: {
      collection: 'pet',
      via: 'owner'
    }
  }
};


// Pet.js
module.exports = {
  attributes: {
    name: {
      type: 'string'
    },

    owner: {
      model: 'user'
    }
  }
};

And I used the following which is the same as the documentation:

User.find()
.populate('pets')
.exec(function(err, users) {
  if(err) return res.serverError(err);
  res.json(users);
});

But I get the following output:

[
  {
    "pets": [],
    "id": "58889ce5959841098d186b5a",
    "firstName": "Foo",
    "lastName": "Bar"
  }
]

Upvotes: 4

Views: 623

Answers (1)

Sayuri Mizuguchi
Sayuri Mizuguchi

Reputation: 5330

If you just need the query for dogs. You could just as easily reverse the query.

Pet.find() //or what you want with {}
 .populate('users')
 .exec(err, petsWithUsers)

But if not:

User.find()
      .populate('pets')
      .exec(err, users) ...

This will return all users (User.find()) and only populate pets of type dog (populate('pets', {type: 'dog'})). In the case you'll have users without dogs in your results.

More information and Reference: here

Upvotes: 2

Related Questions