Currently, I am extracting the days of absence of my colleague from excel files and storing them in a MongoDB database using Mongoose and Express.js.
The process of reading the data is smooth; however, when trying to update the data in the database, an unexpected behavior occurs. When inserting an Object into an array using Array.push(), it results in an Array of Objects containing a single object inside the outer array.
The function provided below retrieves raw data from the excel files and attempts to save it in the database. Please excuse the messy code, as I was only prototyping ;-)
function getDaysOff( data, callback )
{
Member.find({}, function( err, docs ) {
if ( err )
{
console.error( err );
return [];
}
console.log( "found " + docs.length + " team members" );
docs.forEach( function( element ) {
// reset all arrays before continuing
element.days_of_absence = [];
} );
data.forEach( function( element ) {
for ( let i = 0; i < element.length; ++i )
{
var member = element[i];
for ( let j = 0; j < docs.length; ++j )
{
if ( member.name.match( new RegExp( docs[j].name, 'g' ) ) )
{
console.log( member.name + " is " + docs[j].name );
for ( let k = 0; k < member.absent.length; ++k )
{
docs[j].days_of_absence.push( member.absent[k] );
console.log( JSON.stringify( member.absent[k] ) );
}
console.log( JSON.stringify( docs[j].days_of_absence ) );
break;
}
}
}
} );
docs.forEach( function( element ) {
element.save();
} );
callback( docs );
});
}
Here is the schema for the Member:
var mongoose = require('mongoose')
var MemberSchema = new mongoose.Schema(
{
_id: {
type: 'ObjectId'
},
name: {
type: 'String'
},
prename: {
type: 'String'
},
days_of_absence: {
type: 'Array'
}
}
);
module.exports = mongoose.model('Member', MemberSchema, 'members');
When printing days_of_absence
, the output looks like this:
[
[ { "date": "2018-01-28T23:00:00.000Z", "reason": "P" } ],
[ { "date": "2018-01-29T23:00:00.000Z", "reason": "P" } ],
...
[ { "date": "2018-09-27T22:00:00.000Z", "reason": "P" } ]
]
The issue arises with the additional arrays around the objects. I have confirmed that member.absent[k]
contains the desired objects within the inner array. However, I cannot figure out where the extra arrays are coming from. What could be causing this? Any insights or solutions would be much appreciated.
UPDATE
After testing, it has been verified that member.absent[k]
is not an array. The loop displays the intended output console.log( member.absent[k] )
:
{"date":"2018-09-02T22:00:00.000Z","reason":"P"}