Search code examples
sails.jswaterlinesails-mongo

Is there a standard way to expand associations with Sails, Mongo and Waterline with .findOne()?


My models contain associations to other models which are obviously just stored with their ObjectId. What I want to know is if there is a way to pass in the option to expand either all associations or a particular set of associations.

So 'item model' looks like this (example):

module.exports = {

  attributes: {
    name: {
      type: 'string',
      required: true
    },
    description:{
      type: 'string'
    },
    project: {
      model: 'project',
      required: true
    }, ...

When you do:

item.save(function(error, item) { ... })

It will auto expand all associations contained in 'item.' However, if you pass in this option it will not expand:

item.save({ populate: false }, function(error, item) { ... })

I'm wondering why 'save' would auto expand and I'm curious as to if there is a way to have 'findOne' also auto expand. I know you don't want to always expand because it can be hard on memory, but this could be useful to return the fully expanded object at certain times.


Solution

  • You want to populate all associated models?

    Model
        .findOne({name:''})
        .populateAll()
        .exec(
            function(error,result){}
        )
    

    It will populate all associations. If you want to populate only one, you can go with

    Model
        .findOne({name:''})
        .populate('project')
        .exec(
            function(error,result){}
        )
    

    More. You can use 'select', 'where' & 'limit' in populate (works with Mongo)

    Model
        .findOne({name:''})
        .populate('project',{
            {where: {field1: true}},
            {select: ['field1','field2']},
            limit: 3
        })
        .exec(
            function(error,result){}
        )
    

    Of course you can populate few associations

    Model
        .findOne({name:''})
        .populate('project')
        .populate('owner')
        .populate('othermodel')
        .exec(
            function(error,result){}
        )