Sails supports the popular MongoDB database via the sails-mongo adapter.
First, make sure you have access to a running MongoDB server, either on your development machine or in the cloud. Below, 'mongodb://[email protected]/foo' refers to a locally-installed MongoDB using "foo" as the database name. Be sure to replace that connection URL with the appropriate string for your database.
To use MongoDB in your Node.js/Sails app during development:
npm install sails-mongo
in your app folder.In your config/datastores.js
file, edit the default
datastore configuration:
default: {
adapter: 'sails-mongo',
url: 'mongodb://[email protected]/foo'
}
In your config/models.js
file, edit the default id
attribute to have the appropriate type
and columnName
for MongoDB's primary keys:
attributes: {
id: { type: 'string', columnName: '_id' },
//…
}
That's it! Lift your app again and you should be good to go.
To use MongoDB in production, edit your adapter setting in config/env/production.js
:
adapter: 'sails-mongo',
You may also configure your connection URL -- but many developers prefer not to check sensitive credentials into version control. Another option is to use an environment variable:
sails_datastores__default__url=mongodb://heroku_12345678:[email protected]:29017/heroku_12345678
To use MongoDB in your staging environment, edit
config/env/staging.js
. Depending on your application, it may be acceptable to check in your staging database credentials to version control, since they are less of a security risk.
As with all of the Sails database adapters, you can use any of the Waterline model methods to interact with your models when using sails-mongo
.
For many apps, that's all you'll need-- from "hello world" to production. Even if you run into limitations, they can usually be worked around without writing Mongo-specific code. However, for situations when there is no alternative, it is possible to use the Mongo driver directly in your Sails app.
To access the lower-level “native” MongoDB client directly, use the .manager
property of the datastore instance:
// Get access to the native MongoDB client via the default Sails datastore.
var db = sails.getDatastore().manager;
// Find all users who own albums with the word "blue" in the title.
// ("albums" would be defined in `api/models/User.js` as an attribute of type "json".)
db.collection('user').find({"albums.title": {"$regex": /blue/}}).toArray(console.log);
For a full list of methods available in the native MongoDB client, see the Node.js MongoDB Driver API reference.