0
votes

I am using Mongoose to make queries to a MongoDB and I'm running into a strange issue where my second query would cause Mongoose to hang and not return results.

I've created a repo that replicates this issue here. You can clone and run it locally if you wish. Just follow the Usage instructions.

Dataset

name,address,city,state,zip
Jane Doe,123 Main St,Whereverville,CA,90210
John Doe,555 Broadway Ave,New York,NY,10010

One Query

const mongo = new Mongo();

const dataSet1 = await mongo.find('locations', {
  limit: 1,
});
// const dataSet2 = await mongo.find('locations', {
//   limit: 2,
// });

mongo.close();

console.log({
  dataSet1,
  // dataSet2,
});

Here we are querying the locations collection and just returning one document.

Mongoose default connection open to
{ dataSet1:
   [ { _id: 5877b4568f5c931b5f84cd93,
       name: 'Jane Doe',
       address: '123 Main St',
       city: 'Whereverville',
       state: 'CA',
       zip: '90210' } ] }
Mongoose default connection disconnected

As expected, one document is returned.

Two Queries

const mongo = new Mongo();

const dataSet1 = await mongo.find('locations', {
  limit: 1,
});
const dataSet2 = await mongo.find('locations', {
  limit: 2,
});

mongo.close();

console.log({
  dataSet1,
  dataSet2,
});

Here we are making a second query to the locations collection for two documents.

>>> RESTARTING <<<
(node:87245) DeprecationWarning: Calling an asynchronous function without callback is deprecated.
Mongoose default connection open to
^C

The process hangs and does not return anything. Can't quite figure out why this happens.

The Mongo class code can be seen here.

Edit: - Updated code to use native promises but issue still persists.

1
please read here - mongoosejs.com/docs/promises.html they're not complete "promises"Sergey Benner
Thanks, I looked at your link and decided to use native promises. I've updated Mongo.js. It still hangs however with a different warning DeprecationWarning: Calling an asynchronous function without callback is deprecated. Do you think this is related to my issue?purplecones
Use the .then() as they describe it in the documentation. That could be the potential issue but in the case if you want to avoid the use of callbacks etc use the the appropriate libraries like fibers or node-sync etc. Haven't used them in conjunction with mongoose myself though but give it a try if you want. More info here stackoverflow.com/questions/16763890/…Sergey Benner

1 Answers

0
votes

I was able to resolve this by changing the code in Mongo.js from:

db.on('error', (err) => reject(err));
db.on('open', () => {
  model.find(query, fields, options)
    .limit(limit)
    .exec()
    .then(docs => resolve(docs))
    .catch(err => reject(err));
  });
});

to

model.find(query, fields, options)
  .limit(limit)
  .exec()
  .then(docs => resolve(docs))
  .catch(err => reject(err));

I'm not quite sure why the first method caused this error.