Sails: MongoError: failed to connect to server

Created on 24 Jun 2019  ยท  18Comments  ยท  Source: balderdashy/sails

Node version: v10.10.0
Sails version _(sails)_: "^1.2.3"
ORM hook version _(sails-hook-orm)_: "^2.1.1"
Sockets hook version _(sails-hook-sockets)_: "^2.0.0"
Organics hook version _(sails-hook-organics)_:
Grunt hook version _(sails-hook-grunt)_: "^4.0.1"
Uploads hook version _(sails-hook-uploads)_:
DB adapter & version _(e.g. [email protected])_: "sails-mongo": "^1.0.1"
Skipper adapter & version _(e.g. [email protected])_:


Hi everybody,

I need some help.
I can't connect to Atlas mongoDB and I don't understand why.

this is the error that I get:

error: A hook (orm) failed to load!
error: Could not tear down the ORM hook. Error details: Error: Consistency violation: Attempting to tear down a datastore (mongodb) which is not currently registered with this adapter. This is usually due to a race condition in userland code (e.g. attempting to tear down the same ORM instance more than once), or it could be due to a bug in this adapter. (If you get stumped, reach out at http://sailsjs.com/support.)

error: Failed to lift app: Error: Consistency violation: Unexpected error creating db connection

manager:
MongoError: failed to connect to server [cluster0-kqqjs.mongodb.net:27017] on first connect [MongoError: getaddrinfo ENOTFOUND cluster0-kqqjs.mongodb.net cluster0-kqqjs.mongodb.net:27017]

Here's my datastore.js file:

/**
 * Datastores
 * (sails.config.datastores)
 *
 * A set of datastore configurations which tell Sails where to fetch or save
 * data when you execute built-in model methods like `.find()` and `.create()`.
 *
 *  > This file is mainly useful for configuring your development database,
 *  > as well as any additional one-off databases used by individual models.
 *  > Ready to go live?  Head towards `config/env/production.js`.
 *
 * For more information on configuring datastores, check out:
 * https://sailsjs.com/config/datastores
 */

module.exports.datastores = {


  /***************************************************************************
  *                                                                          *
  * Your app's default datastore.                                            *
  *                                                                          *
  * Sails apps read and write to local disk by default, using a built-in     *
  * database adapter called `sails-disk`.  This feature is purely for        *
  * convenience during development; since `sails-disk` is not designed for   *
  * use in a production environment.                                         *
  *                                                                          *
  * To use a different db _in development_, follow the directions below.     *
  * Otherwise, just leave the default datastore as-is, with no `adapter`.    *
  *                                                                          *
  * (For production configuration, see `config/env/production.js`.)          *
  *                                                                          *
  ***************************************************************************/

  mongodb: {

    /***************************************************************************
    *                                                                          *
    * Want to use a different database during development?                     *
    *                                                                          *
    * 1. Choose an adapter:                                                    *
    *    https://sailsjs.com/plugins/databases                                 *
    *                                                                          *
    * 2. Install it as a dependency of your Sails app.                         *
    *    (For example:  npm install sails-mysql --save)                        *
    *                                                                          *
    * 3. Then pass it in, along with a connection URL.                         *
    *    (See https://sailsjs.com/config/datastores for help.)                 *
    *                                                                          *
    ***************************************************************************/
    adapter: 'sails-mongo',
    url:'mongodb://ali:<password>@cluster0-kqqjs.mongodb.net:27017/test?w=majority',
    ssl: true,
  },

My model.js file

/**
 * Default model settings
 * (sails.config.models)
 *
 * Your default, project-wide model settings. Can also be overridden on a
 * per-model basis by setting a top-level properties in the model definition.
 *
 * For details about all available model settings, see:
 * https://sailsjs.com/config/models
 *
 * For more general background on Sails model settings, and how to configure
 * them on a project-wide or per-model basis, see:
 * https://sailsjs.com/docs/concepts/models-and-orm/model-settings
 */

module.exports.models = {


  /***************************************************************************
  *                                                                          *
  * Whether model methods like `.create()` and `.update()` should ignore     *
  * (and refuse to persist) unrecognized data-- i.e. properties other than   *
  * those explicitly defined by attributes in the model definition.          *
  *                                                                          *
  * To ease future maintenance of your code base, it is usually a good idea  *
  * to set this to `true`.                                                   *
  *                                                                          *
  * > Note that `schema: false` is not supported by every database.          *
  * > For example, if you are using a SQL database, then relevant models     *
  * > are always effectively `schema: true`.  And if no `schema` setting is  *
  * > provided whatsoever, the behavior is left up to the database adapter.  *
  * >                                                                        *
  * > For more info, see:                                                    *
  * > https://sailsjs.com/docs/concepts/orm/model-settings#?schema           *
  *                                                                          *
  ***************************************************************************/
  datastore: 'mongodb',
  // schema: true,


  /***************************************************************************
  *                                                                          *
  * How and whether Sails will attempt to automatically rebuild the          *
  * tables/collections/etc. in your schema.                                  *
  *                                                                          *
  * > Note that, when running in a production environment, this will be      *
  * > automatically set to `migrate: 'safe'`, no matter what you configure   *
  * > here.  This is a failsafe to prevent Sails from accidentally running   *
  * > auto-migrations on your production database.                           *
  * >                                                                        *
  * > For more info, see:                                                    *
  * > https://sailsjs.com/docs/concepts/orm/model-settings#?migrate          *
  *                                                                          *
  ***************************************************************************/

  migrate: 'alter',


  /***************************************************************************
  *                                                                          *
  * Base attributes that are included in all of your models by default.      *
  * By convention, this is your primary key attribute (`id`), as well as two *
  * other timestamp attributes for tracking when records were last created   *
  * or updated.                                                              *
  *                                                                          *
  * > For more info, see:                                                    *
  * > https://sailsjs.com/docs/concepts/orm/model-settings#?attributes       *
  *                                                                          *
  ***************************************************************************/

  attributes: {
    createdAt: { type: 'number', autoCreatedAt: true, },
    updatedAt: { type: 'number', autoUpdatedAt: true, },
    id: { type: 'number', autoIncrement: true, },
    //--------------------------------------------------------------------------
    //  /\   Using MongoDB?
    //  ||   Replace `id` above with this instead:
    //
    // ```
    // id: { type: 'string', columnName: '_id' },
    // ```
    //
    // Plus, don't forget to configure MongoDB as your default datastore:
    // https://sailsjs.com/docs/tutorials/using-mongo-db
    //--------------------------------------------------------------------------
  },


  /******************************************************************************
  *                                                                             *
  * The set of DEKs (data encryption keys) for at-rest encryption.              *
  * i.e. when encrypting/decrypting data for attributes with `encrypt: true`.   *
  *                                                                             *
  * > The `default` DEK is used for all new encryptions, but multiple DEKs      *
  * > can be configured to allow for key rotation.  In production, be sure to   *
  * > manage these keys like you would any other sensitive credential.          *
  *                                                                             *
  * > For more info, see:                                                       *
  * > https://sailsjs.com/docs/concepts/orm/model-settings#?dataEncryptionKeys  *
  *                                                                             *
  ******************************************************************************/

  dataEncryptionKeys: {
    default: 'KGQjanQiuFfn7VzbIpgIw9GvJn7FFYs+jf30HzvkzGk='
  },


  /***************************************************************************
  *                                                                          *
  * Whether or not implicit records for associations should be cleaned up    *
  * automatically using the built-in polyfill.  This is especially useful    *
  * during development with sails-disk.                                      *
  *                                                                          *
  * Depending on which databases you're using, you may want to disable this  *
  * polyfill in your production environment.                                 *
  *                                                                          *
  * (For production configuration, see `config/env/production.js`.)          *
  *                                                                          *
  ***************************************************************************/

  cascadeOnDestroy: true


};

My Tasks.js file on the model folder

module.exports = {

  attributes: {

    //  โ•”โ•โ•—โ•ฆโ•โ•—โ•ฆโ•”โ•ฆโ•—โ•ฆโ•”โ•ฆโ•—โ•ฆโ•ฆ  โ•ฆโ•”โ•โ•—โ•”โ•โ•—
    //  โ• โ•โ•โ• โ•ฆโ•โ•‘โ•‘โ•‘โ•‘โ•‘ โ•‘ โ•‘โ•šโ•—โ•”โ•โ•‘โ•ฃ โ•šโ•โ•—
    //  โ•ฉ  โ•ฉโ•šโ•โ•ฉโ•ฉ โ•ฉโ•ฉ โ•ฉ โ•ฉ โ•šโ• โ•šโ•โ•โ•šโ•โ•


    //  โ•”โ•โ•—โ•”โ•ฆโ•—โ•”โ•— โ•”โ•โ•—โ•”โ•ฆโ•—โ•”โ•โ•—
    //  โ•‘โ•ฃ โ•‘โ•‘โ•‘โ• โ•ฉโ•—โ•‘โ•ฃ  โ•‘โ•‘โ•šโ•โ•—
    //  โ•šโ•โ•โ•ฉ โ•ฉโ•šโ•โ•โ•šโ•โ•โ•โ•ฉโ•โ•šโ•โ•


    //  โ•”โ•โ•—โ•”โ•โ•—โ•”โ•โ•—โ•”โ•โ•—โ•”โ•โ•—โ•ฆโ•”โ•โ•—โ•”โ•ฆโ•—โ•ฆโ•”โ•โ•—โ•”โ•—โ•”โ•”โ•โ•—
    //  โ• โ•โ•ฃโ•šโ•โ•—โ•šโ•โ•—โ•‘ โ•‘โ•‘  โ•‘โ• โ•โ•ฃ โ•‘ โ•‘โ•‘ โ•‘โ•‘โ•‘โ•‘โ•šโ•โ•—
    //  โ•ฉ โ•ฉโ•šโ•โ•โ•šโ•โ•โ•šโ•โ•โ•šโ•โ•โ•ฉโ•ฉ โ•ฉ โ•ฉ โ•ฉโ•šโ•โ•โ•โ•šโ•โ•šโ•โ•

  },
  datastore: 'mongodb',
};

Thank you

helpful info or workaround mongo orm

All 18 comments

@AliHammami Thanks for posting! We'll take a look as soon as possible.

In the mean time, there are a few ways you can help speed things along:

  • look for a workaround. _(Even if it's just temporary, sharing your solution can save someone else a lot of time and effort.)_
  • tell us why this issue is important to you and your team. What are you trying to accomplish? _(Submissions with a little bit of human context tend to be easier to understand and faster to resolve.)_
  • make sure you've provided clear instructions on how to reproduce the bug from a clean install.
  • double-check that you've provided all of the requested version and dependency information. _(Some of this info might seem irrelevant at first, like which database adapter you're using, but we ask that you include it anyway. Oftentimes an issue is caused by a confluence of unexpected factors, and it can save everybody a ton of time to know all the details up front.)_
  • read the code of conduct.
  • if appropriate, ask your business to sponsor your issue. _(Open source is our passion, and our core maintainers volunteer many of their nights and weekends working on Sails. But you only get so many nights and weekends in life, and stuff gets done a lot faster when you can work on it during normal daylight hours.)_
  • let us know if you are using a 3rd party plugin; whether that's a database adapter, a non-standard view engine, or any other dependency maintained by someone other than our core team. _(Besides the name of the 3rd party package, it helps to include the exact version you're using. If you're unsure, check out this list of all the core packages we maintain.)_

Please remember: never post in a public forum if you believe you've found a genuine security vulnerability. Instead, disclose it responsibly.

For help with questions about Sails, click here.

@AliHammami Thanks for the detailed example code.
Have you tried setting id: { type: 'string', columnName: '_id' }, under attributes?

@johnabrams7 i've just tried it, I have the same issues.

@AliHammami It looks like it's having trouble reaching cluster0-kqqjs.mongodb.net - I'm curious if the test?w=majority query string part of the URL is possibly confusing the adapter. Is that required and what happens without it?

I don't know if it's required. I deleted it and I have this issue now:

Failed to lift app: Error: Invalid configuration for datastore mongodb: No database could be determined from configuration (tried to use database: undefined).

But if i only delete ?w=majority, I have the same issue:

Failed to lift app: Error: Consistency violation: Unexpected error creating db connection manager:
```
MongoError: failed to connect to server [cluster0-kqqjs.mongodb.net:27017] on first connect [MongoError: getaddrinfo ENOTFOUND cluster0-kqqjs.mongodb.net cluster0-kqqjs.mongodb.net:27017]

This is the uri link from atlas mongodb, maybe it can help you to resolve my problem:
mongodb+srv://ali:@cluster0-kqqjs.mongodb.net/test?retryWrites=true&w=majority

I saw in an another post that I have to delete the +srv and retryWhites=true

@glemiere I've tried it:

adapter: 'sails-mongo',
host: 'localhost',
port: 27017,
database: 'todolist',
user:'ali',
password: 'password',

And I've get this error:

Failed to lift app: Error: Consistency violation: Unexpected error creating db connection manager:
```
MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]

@AliHammami
I found this potential fix on StackOverflow for the same issue with sails-mongo and Atlas mongoDB:

Thank you guys for your help!
I still have the issue :(.

@AliHammami the error you link is showing that you tried to connect to localhost but your server is at cluster0-kqqjs.mongodb.net.

Try:

adapter: 'sails-mongo',
host: 'cluster0-kqqjs.mongodb.net',
port: 27017,
database: 'YOURDBNAMEHERE',
user:'YOURDBUSERHERE',
password: 'YOURPASSWORDHERE',

Just make sure you have the right information at the right place. Do you know your db name? Are you sure your user has read/write access to it?

@glemiere I still have the issue. I know the db name, I have read/write access to it. I tried to connect it with an express.js project and it works fine but I don't understand why it don't want to connect with sails.

@AliHammami - Good to know the credentials are confirmed working. Do you have an example of the working db configuration code from express.js to compare?

DID U FIX THIS?

I have the same problem. I need help

Hey guys I have the same issue and I found the solution on StackOverflow.

Basically you need to update the connection driver version in mongo atlas dashboard from Node.js 3.0 or later driver version to Node.js 2.2.12 or later version.

Thank you @YassineMd for finding that.

Hope this will help @AliHammami @Lozcep @w3villa-mavin

Hey guys I have the same issue and I found the solution on StackOverflow.

Basically you need to update the connection driver version in mongo atlas dashboard from Node.js 3.0 or later driver version to Node.js 2.2.12 or later version.

Thank you @YassineMd! This finally worked!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

3imed-jaberi picture 3imed-jaberi  ยท  3Comments

thomasfr picture thomasfr  ยท  3Comments

alxndrsn picture alxndrsn  ยท  4Comments

randallmeeker picture randallmeeker  ยท  4Comments

kesavkolla picture kesavkolla  ยท  4Comments