Borduhh
Borduhh

Reputation: 2185

Expected to return a value at the end of arrow function when connecting to MongoDB

I am getting the eslint error:

[eslint] Expected to return a value at the end of arrow function. [consistent-return]

I've checked and each path has a return statement. But I feel like my callback function is throwing it for a loop?

Here's the code:

let db;

module.exports.initDb = (callback) => {
  if (db) {
    return callback(null, db);
  }

  MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true }, (err, client) => {
    if (err) {
      return callback(err);
    }

    db = client.db('partsync');
    return callback(null, db);
  });
};

Upvotes: 0

Views: 190

Answers (1)

JPritchard9518
JPritchard9518

Reputation: 192

You have the correct return statements within your MongoClient.connect callback, but you need a return for your parent arrow function initDb. Adding a return statement before MongoClient.connect will fix this. Here is the updated code:

let db;

 module.exports.initDb = (callback) => {
    if (db) {
      return callback(null, db);
    }

    return MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true }, (err, client) => {
      if (err) {
        return callback(err);
      }

      db = client.db('partsync');
      return callback(null, db);
    });
  };

Upvotes: 1

Related Questions