How to connect with mongodb using sailsjs v0.10?

tajuddin picture tajuddin · Feb 6, 2014 · Viewed 22.4k times · Source

Now Using sailsjs v0.10 . Configure connections.js and models.js and change it to connection: 'localMongodbServer' ,installed npm install sails-mongo.

Aftet all this it shows error

 var des = Object.keys(dbs[collectionName].schema).length === 0 ?
                                          ^
TypeError: Cannot read property 'schema' of undefined

at Object.module.exports.adapter.describe (app1_test/node_modules/sails-mongo/lib/adapter.js:70:48)

If change collections.js to adapter.js shows error

  [err] In model (model1), invalid connection :: someMongodbServer
  [err] Must contain an `adapter` key referencing the adapter to use.

Answer

gorelative picture gorelative · Feb 6, 2014

Without seeing code, i can only assume a few things.

  1. You're starting a new sailsjs v0.10 project
  2. You dont have your configuration setup properly.

If this isnt the case, let me know so i can update the answer appropriately.


I have a boilerplate for v0.10 that has a few things baked into it, so you can see how its done. See that repo here

connections.js is the appropriate filename, it was changed in 0.10.

First make sure sails-mongo is installed.

#From your project root run
npm install sails-mongo --save

Next you need to define your connection, and tell sails what adapter to use for models by default. Here is an example of what connections.js and models.js should look like.

connections.js

module.exports.connections = {
  mongodb: {
    adapter   : 'sails-mongo',
    host      : 'localhost',
    port      : 27017,
    user      : '',
    password  : '',
    database  : 'yourdevdb'
  }
}

models.js

module.exports.models = {

  // Your app's default connection.
  // i.e. the name of one of your app's connections (see `config/connections.js`)
  //
  // (defaults to localDiskDb)
  connection: 'mongodb'
};

You can also specify your connections in config/local.js to avoid commiting sensitive data to your repository. This is how you do it.

You dont need to specify all of the contents, as local.js will override whats defined in connections.js Sails will also combine them.

local.js

module.exports = {
  connections: {
      mongodb: {
        host      : 'localhost',
        port      : 27017,
        user      : '',
        password  : '',
        database  : 'yourdevdb'
      }
  }
}

You can even define your adapter in a single model, for instances where you need a single model to talk to a different database type.

You do this by specifying the adapter: in your model..

module.exports = {
  adapter: 'myothermongodb',
},
config: {
  user: 'root',
  password: 'thePassword',
  database: 'testdb',
  host: '127.0.0.1'
},