在Mongoose上手动创建对象列表

时间:2018-04-30 21:32:50

标签: javascript express mongoose model

我正在使用node.JS + Express + Mongoose创建一个Schedule Manager应用程序,我正在尝试在特定的日期和位置搜索约会。如果没有找到约会,我想在开始日期和结束日期之间创建空白约会,以便在我需要时准备好。

问题:

我可以以某种方式返回刚刚创建的约会对象,而不是再次调用Appointments.find吗?如果可能的话,最好的方法是什么?

示例:我想像创建一个新数组并通过迭代添加每个对象。

以下是我的模型的代码:

Appointment.find(query)
    .exec()
    .then((appointments) => {
        if (appointments.length == 0) {
            Location.findById(locationId)
            .exec()
            .then((location) => {
                for (let j = location.available_time_start; j <= location.available_time_end; j += location.appointment_duration) {
                    var newAppointment = new Appointment();

                    newAppointment.start_date = new Date(day.getFullYear(), day.getMonth(), day.getDate(), j);
                    newAppointment.appointment_duration = location.appointment_duration;
                    newAppointment.location = location.id;
                    newAppointment.booked = false;
                    newAppointment.locked = false;

                    Appointment.createAppointment(newAppointment, function (err, appointment) {
                        if (err) throw err;
                        console.log(appointment.location + ' - ' + appointment.start_date);
                    });
                }

                // I WANT TO RETURN THE APPOINTMENTS HERE!
            })
            .catch((err) => {
                console.log("Error while creating appointments: " + err);
            });
        } else {
            // IT RETURNS AS EXPECTED WHEN PREVIOUSLY INCLUDED!
            callback(null, appointments);
        }
    })
    .catch((err) => {
        console.log("Error while searching for appointments: " + err);
    });

1 个答案:

答案 0 :(得分:0)

我通过使用数组解决了这个问题,并在保存每个约会后通过callback函数返回:

                let newAppointments = Array();

                for (let j = location.available_time_start; j <= location.available_time_end; j += location.appointment_duration) {
                    let newAppointment = new Appointment();

                    newAppointment.start_date = new Date(day.getFullYear(), day.getMonth(), day.getDate(), j);
                    newAppointment.appointment_duration = location.appointment_duration;
                    newAppointment.location = location.id;
                    newAppointment.booked = false;
                    newAppointment.locked = false;

                    newAppointments.push(newAppointment);
                    newAppointment.save()
                    .then((appointment) => {
                        console.log(appointment.location + ' - ' + appointment.start_date);
                    })
                    .catch((err) => {
                        console.log("Error while creating appointments: " + err);
                    })
                }

                callback(null, newAppointments);