Reputation: 55
I have this code that takes the value of the number of documents on a given day of the week in MongoDB. And as a return request, the "qweek" array is filled.
function dates(current) {
var week = new Array();
// Starting Monday not Sunday
current.setDate((current.getDate() - current.getDay() + 1));
for (var i = 0; i < 7; i++) {
var dd = String(current.getDate()).padStart(2, '0');
var mm = String(current.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = current.getFullYear();
var day = dd + '/' + mm + '/' + yyyy;
week.push(day);
current.setDate(current.getDate() + 1);
}
return week;
}
// Initialize the App Client
const client = stitch.Stitch.initializeDefaultAppClient("app-id");
// Get a MongoDB Service Client
const mongodb = client.getServiceClient(
stitch.RemoteMongoClient.factory,
"mongodb-atlas"
);
//projection config
const options = { // Match the shape of RemoteFindOptions.
limit: 1000, // Return only first ten results.
projection: { // Return only the `title`, `releaseDate`, and
day: 1, // (implicitly) the `_id` fields.
},
sort: { // Sort by releaseDate descending (latest first).
releaseDate: -1,
},
}
// Get a reference to the travels database
const db = mongodb.db("travels");
function displayCountTravels() {
var daysweek = dates(new Date());
var qweek = new Array();
for (var l = 0; l < daysweek.length; l++) {
db.collection("details")
.find({
"day": daysweek[l]
}, options)
.toArray()
.then(docs => {
qweek.push(docs.length);
});
}
console.log(qweek);
console.log(qweek[1]);
return qweek;
}
In this case, when I make a request in the array console. I get this return:
console.log(qweek);
Log output:[]
0: 0
1: 0
2: 0
3: 2
4: 0
5: 0
6: 0
length: 7
__proto__: Array(0)
Return of command console.log(week);
But when I try to get the value by the index. The array item is returned with undefined.
console.log(qweek[1]);
Log output:
undefined
Return of command console.log(week[1]);
I would like to know why the value comes with undefined
.
Upvotes: 2
Views: 1659
Reputation: 3529
Essentially this is a case of asynchronous
behavior in Javascript. On top of that asynchronous
calls are made in a for..loop
.
Short explanation: The mongo-db query calls are async
in nature and the execution is not going to wait for it finish before reaching the console.log(qweek)
which is outside the then
block. As a result you'll be getting qweek
as empty[] or qweek[1]
as undefined.
Couple of ways solve this is Serializing with promises and async/await
or using Promise.all()
. Would suggest you to read upon them to understand more.
Using async/await
: Syntax wise less verbose and easy to comprehend
async function displayCountTravels() {
var daysweek = dates(new Date());
var qweek = [];
try {
for (var l = 0; l < daysweek.length; l++) {
/*wait for the promise to resolve before next iteration*/
var docs = await db
.collection("details")
.find({ day: daysweek[l] }, options).toArray();
qweek.push(docs.length);
}
} catch (e) {
console.error(e);
}
console.log(qweek);
console.log(qweek[1]);
return qweek;
}
Using Promise.all(...)
:
function displayCountTravels() {
var daysweek = dates(new Date());
var promises = [];
/*each mongo query is a promise, collect and return*/
for (var l = 0; l < daysweek.length; l++) {
promises.push(
db.collection("details").find({ day: daysweek[l] }, options).toArray()
);
}
return Promise.all(promises);
}
/*Calling fn, getting results in then since Promise.all() itself is promise*/
displayCountTravels()
.then((results) => {
/*using map to get lengths of the documents returned and put it in qweek*/
var qweek = results.map((e) => e.length);
console.log(qweek);
console.log(qweek[1]);
})
.catch((e) => {
console.error(e);
});
Upvotes: 1