Luc
Luc

Reputation: 17072

Query model against value within a list

When I query a user from its email:

User.findOne({email: '[email protected]'}).done(function(err, u){console.log(u.sessionTokens);})

I got its tokens list:

[ { token: '8dfe6aa0-2637-4b3f-9a3c-3ae8dc225b77',
    issuedAt: Tue Jan 14 2014 14:40:22 GMT+0100 (CET) } ]

But when I query a token within this list it does not retrieve the user:

User.findOne({'sessionTokens.token':'8dfe6aa0-2637-4b3f-9a3c3ae8dc225b77'}).done(function(err, u){console.log(u);})

=> undefined

Any ideas ? Does the User.findOne({'sessionTokens.token':'8d...77'}) is a correct query ?

EDIT

My User model is something like:

module.exports = {

  schema: true,

  attributes: {

    email: {
      type: 'email',
      required: true
    },

    encryptedPassword: {
      type: 'string'
    },

    sessionTokens: {
      type: 'array'
    },
    ...
  }
}

sessionToken is an attribute of type Array. This array contains several object like:

{ token: '8dfe6aa0-2637-4b3f-9a3c-3ae8dc225b77',
issuedAt: Tue Jan 14 2014 14:40:22 GMT+0100 (CET) }

EDIT

I've tested with mongo-sails instead of mongo-disk, this is working fine but as Chad pointed this out, it depends of the adapter used.

Upvotes: 1

Views: 148

Answers (1)

Chad
Chad

Reputation: 2289

With the help of robdubya & sfb_ in #sailsjs@freenode, we discussed a solution for this a bit. The answer depends on the adapter you are using. The adapter that I am most familiar with is the mysql adapter, and in that adapter, the 'array' attribute type gets serialized to the database as a JSON string. So in that case, using the 'contains' modifier on the query of the model would allow you to find the record you are looking for:

var criteria = {
  sessionToken: {
    contains: '8dfe6aa0-2637-4b3f-9a3c-3ae8dc225b77'
  }
};

User.findOne(criteria).done(function (err, user) {
  ...
});

Upvotes: 2

Related Questions