Перебирать все документы в коллекции MongoDB и сохранять данные в массиве. - PullRequest
0 голосов
/ 11 июля 2020
• 1000 c поле пользователя или все данные этого пользователя. Я могу видеть каждый документ, напечатанный на консоли, но после перебора всех документов мой массив все еще пуст при печати. В чем я ошибаюсь и если есть альтернативный подход, дайте мне знать.
const mongoose = require('mongoose');
let Users = require('./models/user.model');

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex:true, useUnifiedTopology: true});
const connection = mongoose.connection;
connection.once('open', () => {
    console.log("MongoDB connection success");
})

let arr = [];
async function getRecords() {
    let cursor = Users.find({}).cursor();
    for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
        arr.push(doc);     //does not work :(
        console.log(doc);  //this works
    }
}

getRecords();
console.log("ARRAY:",arr);  //prints []

1 Ответ

0 голосов
/ 11 июля 2020

Предложение

Ваш код должен читаться как таковой

let arr = [];

// This is an async function (returns a promise)
async function getRecords() {
    let docs = await Users.find({}).lean();
    arr = docs.filter((doc) => doc !== null); // As an example, however, enter appropriate condition for filter
    return arr;
}

// Call the async funtion
getRecords().then(docs => {
  console.log("ARRAY:", arr); 
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...