2

I'm newbie of Sails and I've got a problem with one to one association. First, I have model User:

module.exports = {
  schema: true,
  identity : "User",
  tableName: "user",
  attributes: {
    email: {
      type: 'email',
      unique: true,
      required: true
    },

    password: {
      type: 'string'
    },

    salt: {
      type: 'string'
    },

    merchant: {
      model: 'merchant',
      defaultsTo: null
    },

    removed: {
      type: 'boolean',
      required: true,
      defaultsTo: false
    }
  }
}

And my Merchant model:

module.exports = {
  schema: true,
  identity : "Merchant",
  tableName: "merchant",
  attributes: {
    name: {
      type: 'string',
      unique: true,
      required: true
    },

    code: {
      type: 'string',
      unique: true,
      required: true
    },

    security_key: {
      type: 'string',
      required: true
    },

    active: {
      type: 'boolean',
      defaultsTo: false,
      required: true
    },

    user: {
      model: 'user'
    }
  }
}

So when I need to find records where merchant.active = true, I write this query:

var findUser = User.find(query).populate('merchant', {active: true});
return findUser;

But it was not working at all.

Anyone any ideas to solve this properly?

P.S. my Sails version is: 0.11.1. My DB is MongoDB

Chris Montanaro
  • 16,948
  • 4
  • 20
  • 29
Savior Nguyen
  • 87
  • 1
  • 10

1 Answers1

1

First of all, remove defaultsTo from your association attributes. I don't like this :) I don't know if it makes the problem, but in documentation I never see this.

Also you need to execute your query, not just return it. If I take your models' declarations then I can write populate query like this.

var findUser = User.find(query).populate('merchant', {active: true});

findUser.then(function(user) {
  console.log('Your user is ' + user);
}).catch(function(error) {
  console.log('Your error is ' + error);
});
Eugene Obrezkov
  • 2,910
  • 2
  • 17
  • 34
  • my full code is: function findUser() { var findUser = User.find(query).populate('merchant', {active: true}); return findUser; } findUser().exec(function (err, users) { //Do somthing but user[0].merchant.active still get active=false }); – Savior Nguyen Sep 13 '15 at 08:08
  • 1
    Did you try remove `populate('merchant')` and make `query` like this `'merchant.active': true` ? – Eugene Obrezkov Sep 13 '15 at 08:59
  • Yes, I did but still not working. May be waterline orm not support one to one populate conditions :( – Savior Nguyen Sep 16 '15 at 07:14
  • @SaviorNguyen just saw the answer here - http://stackoverflow.com/a/32591367/2357633. Seems that Waterline is not properly support one-to-one associations. – Eugene Obrezkov Sep 16 '15 at 08:17