1

I'm using SailsJS, so Waterline ORM and MongoDB.

I'm saving multiple user IDs in an object within a collection called Labels (this is so that a label can belong to multiple users).

I have a data structure in Mongo something like this:

labels: {
    id: ...
    belongs_to: {
        **id of user**: 2 (I'm using this is for individual user ordering)
    }
}

If I'm currently user of id 101 - I want to find() all Label entries where 101 exists in labels.belongs_to.

I've searched the docs but can't find how to do this.

I've tried (with no luck) something similar to:

Label.find().where({ belongs_to: {'contains' : user_id})

Is this the best way to tackle this, and if so, how can I achieve this via Sails?

mcnamee
  • 508
  • 1
  • 5
  • 11

1 Answers1

3

Currently Waterline does not support querying embedded records, mostly because this is not simple to do across multiple DBs.

You can however use Label.native(function(err, rawMongoCollection){/*...*/}); to get a raw Mongo collection and with it you should be able to do a similar query: .native() docs.

Dário
  • 2,002
  • 1
  • 18
  • 28
  • Thanks Dário - any tips on the actual query? I can't seem to pass variables into the where. Eg. collection.find({ "label_belongs_to[**user_id**]" : {$gt: -1} }) - where user_id is the logged in user id. This results in a syntax error because of the [] – mcnamee Jun 10 '15 at 20:58
  • Is `collection` in your example a raw mongo collection? I'm no mongo expert but I believe it expects dot '.' notation, so something like `collection.find({ "label_belongs_to.user_id" : {$gt: -1} })`. – Dário Jun 11 '15 at 10:57