G
G
Grish Poghosyan2021-08-05 13:52:29
JavaScript
Grish Poghosyan, 2021-08-05 13:52:29

Is it possible to skip null?

Here is the model

const schema = new Schema({
    // ....
    conditions: {},
    // ....
});


Conditions is a nested document and you can store anything in it with any key (well, a little differently. There will be fields from another model, but some may be missing). And let's say in our conditions:

{
    "conditions": {
        "age": 10,
        "name": "John"
    }
}


It's at the base. Now, I want to find this document, but because I don't know what fields are there, I'm running into a problem...

const conditions = {
    'conditions.age': 10,
    'conditions.name': 'John',
    'conditions.surname': 'White' // surname там нет
}
const result = await Model.find(conditions);
console.log(result) // [];


And the question is, is it possible to exclude from the filter fields that are not in the document? So that find simply skips them, does not take them into account ... Thanks in advance. )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Grish Poghosyan, 2021-08-05
@hovsepyann

Decision

const validConditions = {
    $and: [
      {
        $or: [
          { 'conditions.age': { $exists: false } },
          { 'conditions.age': 20 },
        ],
      },
      {
        $or: [
          { 'conditions.name': { $exists: false } },
          { 'conditions.name': 'John' },
        ],
      },
      {
        $or: [
          { 'conditions.surname': { $exists: false } },
          { 'conditions.surname': 'White' },
        ],
      },
    ],
  };

  const result = await Test.find(validConditions);

It was enough just to write a query for SQL ...
SELECT * FROM entries WHERE age = 20 OR age IS NULL AND name = 'John' OR name IS NULL AND surname = 'White' OR surname IS NULL

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question