How to connect with mongodb using sailsjs v0.10?

怎甘沉沦 提交于 2019-11-30 00:23:02

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'
},

If you are working with v0.10, you need to install sails-mongo from v0.10 branch on Github, 'cause the Waterline adapter API was changed in v0.10. In your package.json put

"sails-mongo": "https://github.com/balderdashy/sails-mongo/archive/v0.10.tar.gz"

then run npm install.

In config/connections.js you should have MongoDB adapter described, and in your config/models.js this adapter must be referenced.

That's it, sails lift should work after that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!