0

I execute a MongoDB request and it returns the Array objectArray instead the object object!

// Exec request
return MDBObject.find({}, (err, objectArray) => {
  var object = null;
  if (err) {
    return Promise.reject(err);
  } else {
    // Check
    if (objectArray && objectArray.length > 0) {
      object = objectArray[0];
    }
    // Ok
    return object;
  }
}

But when I use this, it works:

return new Promise((resolve, reject) => {
  // Exec request
  return MDBObject.find({}, (err, objectArray) => {
    var object = null;
    if (err) {
      reject(err);
    } else {
      // Check
      if (objectArray && objectArray.length > 0) {
        object = objectArray[0];
      }
      // Ok
      resolve(object);
    }
  }
});

Any clue why the first option does not work?

Regards, Serge.

LucasBrazi06
  • 117
  • 13
  • You must use a promise `then` callback for that, not the `find` callback! – Bergi Apr 05 '17 at 07:51
  • Mongoose async operations [already return promises](http://mongoosejs.com/docs/promises.html), no need to wrap them. – robertklep Apr 05 '17 at 10:44
  • Yes but the find() callback method includes the 'err' in addition to the result which the then() method does not. Does it trigger an exception or a reject? – LucasBrazi06 Apr 05 '17 at 12:21

0 Answers0