简体   繁体   English

数组未添加到数组中的对象

[英]Array not added to object in array

I want to combine two arrays from MongoDB: an array of contact objects and an array of appointments. 我想组合来自MongoDB的两个数组:联系人对象数组和约会数组。

My current solution is to query all contacts and appointments, loop over each array, compare the email and if they match, add each appointment to its corresponding contact. 我当前的解决方案是查询所有联系人和约会,遍历每个数组,比较电子邮件,如果匹配,则将每个约会添加到其对应的联系人。

    var contacts, appointments;
    Contact.find(query, function(err, result1) {
        if (err) {
            console.log(err)
        }
        else {
            contacts  = result1;

            Appointment.find({isArchived : false}, function(err, result2) {
                if (err) {
                    console.log(err);
                }
                else {

                    appointments = result2;
                    for (var i=0; i<contacts.length;i++) {
                        contacts[i]["appointments"] = [];
                        for (var j=0; j<appointments.length;j++) {
                            if (contacts[i].email === appointments[j].owner) {                                    
                                contacts[i].appointments.push(appointments[j]);
                            }
                        }
                    }
                    res.send(contacts);

                }                    
            });
        }            
    });

Contacts: 联系人:

 [{ email: "example1@example1.com" }, { email: "example2@example2.com" }] [{ email: "example1@example1.com", start: "2015-01-01", end: "2015-02-01" }, { email: "example1@example1.com", start: "2015-02-01", end: "2015-03-01" }] // Desired output [{ email: "example1@example1.com", appointments: [{ email: "example1@example1.com", start: "2015-01-01", end: "2015-02-01" }, { email: "example1@example1.com", start: "2015-02-01", end: "2015-03-01" }] }, { email: "example2@example2.com", appointments: [] }] 

I know it's a mess, and I'm also unable to append the appointment array to each contact. 我知道那是一团糟,而且我也无法将约会数组附加到每个联系人。 I can only assign values to existing object keys. 我只能将值分配给现有的对象键。

So it's really two questions: 1) Why can't I append the array to an existing contact, 2) what is a more efficient solution? 因此,实际上有两个问题:1)为什么我不能将数组附加到现有联系人上,2)什么是更有效的解决方案?

Apparently you cannot extend Mongoose results directly. 显然,您不能直接扩展猫鼬的结果。 For that to work, you must call .toObject() on the object you wish to extend. 为此,必须在要扩展的对象上调用.toObject()。

I would love to have suggestions for a cleaner solution, preferrably one that only involves one mongodb call, and no manual array operations. 我很乐意为您提供一种更清洁的解决方案的建议,最好是只涉及一个mongodb调用,而无需手动数组操作的解决方案。

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

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