简体   繁体   中英

Why is my callback not working correctly?

This method runs at node server

const express = require("express");
const app = express();

const fs = require("fs");
const connectDb = require("./config/db");

const __init__ = (local = false) => {
  fs.writeFile(
    "./config/default.json",
    `{
        "mongoURI": ${
          local
            ? `"mongodb://127.0.0.1:27017/test"`
            : `"mongodb+srv://admin:<password>@abc-xxghh.mongodb.net/test?retryWrites=true&w=majority"`
        }
      }`,

    function(err) {
      if (err) {
        return console.log(err);
      }

      connectDb();
    }
  );
};

__init__(true);

The problem is that if originally mongoURI: 127.0.0.1:27017 , and if I do __init__(false) , Node will try to connect to 127.0.0.1:27017 , when it should be connecting to +srv uri.

If I run __init__(false) AGAIN, then it will connect to appropriate link.

Likewise, if I then run __init__(true) , it will connect to srv+ when it should be connecting to local, and if I run __init__(true) again, only then it will connect to local.

What am I doing wrong here? I'm using the callback as Im supposed to, no?


Edit:

//config/db
// for mongoDB connection
const mongoose = require("mongoose");
// require the directory
const config = require("config");
// get all contents of JSON file
const db = config.get("mongoURI");

const connectDb = async () => {
  try {
    console.log("connecting to mongodb", db);
    await mongoose.connect(db, {
      useNewUrlParser: true,
      useCreateIndex: true,
      useFindAndModify: false,
      useUnifiedTopology: true
    });

    console.log("Mongo DB connected");
  } catch (err) {
    console.log("unable to connect to mongodb");
    console.log(err.message);
    //exit if failure
    process.exit(1);
  }
};

module.exports = connectDb;

I've even tried doing the following:

.....
  console.log("Developing locally:", local);

  // require the directory
  const config = require("config");
  // get all contents of JSON file
  const db = config.get("mongoURI");
  connectDb(db);
.....

But it still reads the old value

The problem is on execution order since the require is sync

The order now is:

  1. const connectDb = require("./config/db");
  2. const config = require("config");
  3. const db = config.get("mongoURI"); // this has the OLD VALUE
  4. fs.writeFile(...
  5. await mongoose.connect(db, { // this is using the OLD REFERENCE

So you need to change your connectDb function like this:

const connectDb = async () => {
  const config = require("config");
  // get all contents of JSON file
  const db = config.get("mongoURI");

  try {
    console.log("connecting to mongodb", db);
    await mongoose.connect(db, {
      useNewUrlParser: true,
      useCreateIndex: true,
      useFindAndModify: false,
      useUnifiedTopology: true
    });

    console.log("Mongo DB connected");
  } catch (err) {
    console.log("unable to connect to mongodb");
    console.log(err.message);
    //exit if failure
    process.exit(1);
  }
};

Anyway, I think this is not a nicer way to load config based on the environment, so I would suggest improving it using factory pattern.

Your code for URL local vs srv+ is correct. Problem i could see is placement of method connectDb();

fs.writeFile("fir arg - URL", "second -content", third - error fun {});

where in your code after function, connectDb() is placed after error fun. After it should be closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM