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.
![Return of command "console.log(week[1]);"](https://mapledrawhubb.com/i.sstatic.net/u8Lk3.png)
consoleprint the values. Most likely what is happening is: theconsole.logofqweekis inside thethen()block andconsole.log(qweek[1]);is outside.