4

In LokiJS I try a very simple query (which I assume is AND):

var dbRes = recsCol.find({'format':format, 'cardId':-1});

after inserting some data with

recsCol.insert({format:format, cardId:id, recCardId:key, amount:item[key]});

that doesn't contain a cardId of -1.

The query still yields results. Is this expected behaviour? If so, how can I make the fields match exactly so that I won't get a result in this case?

Community
  • 1
  • 1
Wonko
  • 176
  • 1
  • 9

2 Answers2

6

You can do an AND in LokiJS, no problem:

var dbRes = recsCol.find({'$and': [{'format':format}, {'cardId':-1}]});

I recommend using find for one-off queries. If the query occurs multiple times on resultsets that may change then definitely use a view.

Joe Minichino
  • 2,793
  • 20
  • 20
  • This will do the same thing. Each field needs to be in its own query object for it to be an AND. – Alex K Apr 22 '16 at 18:01
  • 1
    @AlexKinnee you are right, some oversight for me seeing as i wrote LokiJS ! I updated the answer, thanks. – Joe Minichino Apr 23 '16 at 06:59
  • 1
    @AlexKinnee i also upvoted your answer as it was actually the correct one, but my one was marked as correct so i didn't want people to get misinformed. – Joe Minichino Apr 23 '16 at 07:10
4

By default, all fields in a query object are treated as an OR. To make it an AND you will need to change your query syntax to the following:

recsCol.find({
    $and: [
        {'format':format},
        {'cardId':-1}
    ]
});
Alex K
  • 14,893
  • 4
  • 31
  • 32