简体   繁体   English

遍历 MongoDB 集合中的所有文档并将数据保存在数组中

[英]Iterate through all documents in a MongoDB collection and saving the data in array

I thought this would be a straightforward task but what I am trying to do is go through all the documents (users) in my collection using a cursor and saving some data into a JS array or set about a specific field of the user or all of the data on that user.我认为这将是一项简单的任务,但我想要做的是 go 使用 cursor 通过我的集合中的所有文档(用户)并将一些数据保存到 JS 数组或设置用户的特定字段或所有该用户的数据。 I am able to see each document printed on the console, but after looping through all the documents, my array is still empty when printed.我可以在控制台上看到打印的每个文档,但是在遍历所有文档后,打印时我的数组仍然是空的。 Where am I going wrong and if there is an alternative approach please let me know.我哪里错了,如果有其他方法,请告诉我。

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 []

Suggestion建议

Your code should read as such您的代码应该这样读

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); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM