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

Array not added to object in array

本文关键字:数组 对象 添加      更新时间:2023-09-26

我想结合MongoDB中的两个数组:联系人对象数组和约会数组。

我目前的解决方案是查询所有联系人和约会,遍历每个数组,比较电子邮件,如果它们匹配,将每个约会添加到相应的联系人。

    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);
                }                    
            });
        }            
    });

联系人:

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

我知道这很乱,我也无法将约会数组附加到每个联系人。我只能给现有的对象键赋值。

所以这实际上是两个问题:1)为什么我不能将数组附加到现有联系人,2)什么是更有效的解决方案?

显然你不能直接扩展Mongoose的结果。要做到这一点,您必须在希望扩展的对象上调用. toobject()。

我很想有一个更干净的解决方案的建议,最好是一个只涉及一个mongodb调用,没有手动数组操作。