Skip to content Skip to sidebar Skip to footer

Mongoose Multiple Synchronous Find To Reuse Object Id

My models has lot of relationship between each object and when I want to search some data I have to find the previous object and it makes me to write lot of callback. I have 4 mode

Solution 1:

You can wrap each findOne function into the promise and use await from Babel. In this case, your code may look like this:

let office = awaitnewPromise((resolve, reject) => {
    Office.findOne({ geolocation: origin._id}, function(err, office){
        if (err) reject(err)
        resolve(office)
});

let company = awaitnewPromise((resolve, reject) => {
    Company.findOne({ _id: office.company }, function(err, company){
        if (err) reject(err)
        resolve(company)
});
... and so on

Or, maybe you want to read about population in MongoDB: http://mongoosejs.com/docs/populate.html

Post a Comment for "Mongoose Multiple Synchronous Find To Reuse Object Id"