Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

moleculer-db-adapter-mongoose connect function resolves the Promise even when there is no connection established #91

Open
segpacto opened this issue Apr 24, 2019 · 1 comment

Comments

@segpacto
Copy link

segpacto commented Apr 24, 2019

The problem comes when the adapter-mongoose is used with multiple services which doesnt have dependencies between each other.

Service A

module.exports = {
	 name: "testA",
	  mixins: [DbService],
	  adapter: new MongooseAdapter("mongodb://localhost/test"),
	  model: ModelForServiceA,
	  afterConnected() {
		  this.logger.info("Connected successfully A...");
	  }
}

Service B

module.exports = {
   name: "testB",
   mixins: [DbService],
   adapter: new MongooseAdapter("mongodb://localhost/test"),
   model: ModelForServiceB,
   afterConnected() {
		this.logger.info("Connected successfully B...");
   }
}

if the mongodb server is down then Service B is going to report wrongly "Connected successfully B..." .
The reason was nailed to the connect function of MongooseDbAdapter :

connect() {
		let conn
		if (this.model) {
			if (mongoose.connection.readyState != 0) {
				this.db = mongoose.connection;
				return Promise.resolve();
			}

			conn = mongoose.connect(this.uri, this.opts);
		} else if (this.schema) {
			conn = mongoose.createConnection(this.uri, this.opts);
			this.model = conn.model(this.modelName, this.schema);
		}

		return conn.then(result => {
			this.db = result.connection || result.db;

			this.db.on("disconnected", function mongoDisconnected() {
				/* istanbul ignore next */
				this.service.logger.warn("Disconnected from MongoDB.");
			}.bind(this));
		});
}

while executing service B it checks for mongoose.connection.readyState and after readyState 2 = connecting the Promise resolves simply because the status is connecting.
However under normal connection behavior this function resolves only when the connection is established.
This provokes the function afterConnected to be executed while there is no connection established.
Is there any different way to solve this issue without setting a dependency between services or using the schema instead of the model ?

@segpacto segpacto changed the title moleculer-db-adapter-mongoose report wrong connection state moleculer-db-adapter-mongoose connect function resolves the Promise even when there is no connection established Apr 24, 2019
@segpacto
Copy link
Author

Anyone have a suggestion ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant