简体   繁体   English

Array.push(Object)插入对象数组

[英]Array.push(Object) inserts array of objects

I'm currently trying to read the days of absence of my colleague from our excel files and store them in a mongodb using mongoose and express-js. 我目前正在尝试从我们的excel文件中读取同事缺席的日子,并使用mongoose和express-js将它们存储在mongodb中。

Reading the data works fine, but updating the data in the db always produces the strange behavior, where inserting an Object into an array using Array.push() results in an Array of Objects containing a single object inside the outer array. 读取数据可以正常工作,但是更新db中的数据总是会产生奇怪的行为,即使用Array.push()将对象插入到数组中会导致对象数组包含外部数组内的单个对象。

The function below gets the raw data from the excel files and attempts to store them in the db. 下面的函数从excel文件获取原始数据,然后尝试将其存储在数据库中。 Please ignore the code-mess, I was just 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 befor 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 );
    });
}

And here is the Member schema: 这是成员架构:

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 it yields something like this: 当打印days_of_absence它会生成如下内容:

[
  [ { "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" } ]
]

Where members.absent[k] is equal to the objects inside the inner array. 其中members.absent[k]等于内部数组内的对象。 (I already checked that). (我已经检查过了)。 However I have no clue where the arrays around the objects come from. 但是我不知道对象周围的数组来自哪里。 What am I missing? 我想念什么? What I want is some 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" }
]

UPDATE UPDATE

As suggested I already tested if member.absent[k] is an array however printing it in the loop revealed that it isn't. 如建议的那样,我已经测试了member.absent[k]是否为数组,但是在循环中打印它表明不是。 console.log( member.absent[k] ) yields the desired: console.log( member.absent[k] )产生所需的结果:

{"date":"2018-09-02T22:00:00.000Z","reason":"P"}

It looks like, you have an array for member.absent[k] . 看起来,您有一个member.absent[k]数组。 You could spread it and get a single object. 您可以传播它并得到一个对象。

docs[j].days_of_absence.push(...member.absent[k]);

I you do not know if the value is always an array, you could make one and spread it. 我不知道该值是否总是一个数组,您可以创建一个并进行传播。

docs[j].days_of_absence.push(...(
    Array.isArray(member.absent[k])
        ? member.absent[k]
        : [member.absent[k]]
));

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

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