Фильтрация документа Mongoose, который содержит массив объектов - PullRequest
0 голосов
/ 20 октября 2019

Я хотел бы знать, как получить документы в MongoDB, используя mongoose, для которых все имеют значение true для свойства done в массиве объектов. Примерно так: этот должен быть найден:

    _id : xxxx,
    step:
    [{name : "step1", done : true},
    {name : "step2", done : true},
    {name : "step3", done : true}
    {name : "step4", done : true}
    ]
    otherProperty : "random string ...",
    ...,
    __v : 0
------

этот должен игнорироваться

    _id : xxxx,
    step:
    [{name : "step1", done : true},
    {name : "step2, done : true},
    {name : "step3", done : false}
    {name : "step4", done : true}
    ]
    otherProperty : "random string ...",

Спасибо

Ответы [ 2 ]

0 голосов
/ 20 октября 2019

попробуйте таким образом

 let data = [{_id : 'xxxx',
    step:
    [{name : "step1", done : true},
    {name : "step2", done : true},
    {name : "step3", done : true},
    {name : "step4", done : true}
    ],
    __v : 0
  },{_id : 'xxxx',
    step:
    [{name : "yuty", done : true},
    {name : "step2", done : false},
    {name : "step3", done : true},
    {name : "step4", done : true}
    ],
    __v : 0
  }];
let finalDta = data.filter(d=>
  !d.step.map(done=>done.done).includes(false)
)
console.log(finalDta)
0 голосов
/ 20 октября 2019

Следующий код получит все документы из коллекции MongoDB, итерирует их, чтобы проверить, какие из них выполнили все шаги успешно, а затем распечатает те, которые выполнили все шаги.

const mongoose = require( "mongoose" );
const Schema   = mongoose.Schema;
const Model    = mongoose.model;

const StepSchema = new Schema({
    step: [Object],
    name: String
});


Step = Model( "Step", StepSchema );

mongoose.connect( "mongodb://localhost:27017/chummy", { useNewUrlParser: true, useUnifiedTopology: true } );

Step.find( {}, (err, docs) => {  // Get all the documents from the COllection.

    docs.forEach(doc => {  // Select the documents one by one.

        let success = true; // Set a variable that will tell whether the document completed all the steps or not.

        doc.step.forEach( s => {  // Select each step one by one.
            if(!s.done == true) {  // Check if the step was done or not e.g. s.done = true
                success = false;    // If the step was not done, then change success to false.
                return; // Since a step failed, there's no need to continue checking the rest.
            }
        } );

        if(success) {     // Check if success is still true.
            console.log(doc);  // If all the steps were completed, success will stay true and the document will be logged.
        }

    });

} );

Примечание: это весь код, и этот код был протестирован на Ubuntu 19.04 Desktop с NodeJS 10.16.3, NPM 6.9.0 и Mongoose 5.7.5

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...