Search code examples
node.jstypescriptmongodbmongoosees6-promise

Why does my async code not work properly unless I log the promise?


I have some async code that makes calls to a mongo database and inserts/fetches items. When I am developing locally, the code below works fine. However, when I make the mongoose instance connect to MongoDb Atlas, issues arise. In particular, it seems that my code does not work properly unless I console.log the promise, which makes no sense to me. For example, with the console.log statement, all my tests pass as expected. Without it, 35 tests fail... This is because the promise I am expecting returns null, when it should return some JSON object from the database. Is my code not blocking properly?

It feels like I'm dealing with Schrodinger's cat... Any help would be appreciated. Thanks in advance.

Below is an example promise/function call. I then pass it into _executeQuery. I have await on relevant functions, so I don't think it's because I'm missing the word await somewhere.

async _inSomeAsyncFunction = () => {
      const dbQueryPromise = this._dbModel.findById(_id, modelView).lean();
      await this._executeQuery({ dbQueryPromise, isAccessPermitted: true })
}

_executeQuery basically gets the result of the promise if the user has access.

private _executeQuery = async (props: {
    isAccessPermitted: boolean;
    dbQueryPromise: Promise<any>;
  }): Promise<any> => {
    const { isAccessPermitted, dbQueryPromise } = props;

    if (!isAccessPermitted) {
      throw new Error('Access denied.');
    }
    console.log(dbQueryPromise, 'promise'); // without this line, dbQueryResult would be null...
    const dbQueryResult = await dbQueryPromise;
    return dbQueryResult;
  };

After some more testing, I found out that the first API call works but any calls after that returns null...

EDIT:

this._dbModel is some mongoose schema. For example,

 const dbSchema= new Schema({
    name:  String,
  });

 const dbModel = mongoose.model('DbSchema', dbSchema);

Solution

  • Try replacing your dbQueryPromise as follows:

     const dbQueryPromise = this._dbModel.findById(_id, modelView).lean().exec();
    

    Mongoose queries do not get executed unless you pass a callBack function or use exec()