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. 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 []
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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.