Monday, 10 April 2017

How to return documents by mongoose find?

In my application, Im using mongoose with bluebird like this:

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');

In the same file, Im holding an function which searches for "appointment"-documents in the Database. The return of that function should be the resulting array of found documents and not a promise, a query or something else.

But unfortunately, it seems like the program will jump back to the calling function before the promise will get fulfilled. So how can I handle that?

Here's my function in the current state:

get_intersecting_appointment: function(appointment) {

        var appointmentQuery = AppointmentModel.find({
            $and: [{
                    begin: {
                        $lte: appointment.begin
                    }
                },
                {
                    end: {
                        $gte: appointment.end
                    }
                }
            ]
        });

        return appointmentQuery.then(function(appointments) {
            debug("Found appointments:");
            debug(appointments);

            if (appointments) {
                return appointments;
            } else {
                return [];
            }

        });


    },

Hint: The calling function prints the "next debug-outputs" before the inner debug("Found appointments:"); from above. Lets say, the calling function looks like this:

appointment_is_available: function(appointment) {

        var appointments = dbcon.get_intersecting_appointment(appointment);
        //...
}



via Marc M

No comments:

Post a Comment