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://root@localhost/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://root@localhost/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.
After configuring your project to use MongoDB, you may notice that your Waterline queries are now case-sensitive by default. To do case-insensitive queries, you can use .meta({makeLikeModifierCaseInsensitive: true})
.
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:random_password@ds029017.mLab.com: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.
As of sails-mongo
v2.0.0 and above, you can access the MongoClient
object via manager.client
. This gives you access to the latest MongoDB improvements, like ClientSession
,
and with it, transactions, change streams, and other new features.
var mongoClient = Pet.getDatastore().manager.client;
var results = await mongoClient.db('test')
.collection('pet')
.find({}, { name: 1 })
.toArray();
console.log(results);
For a full list of methods available in the native MongoDB client, see the Node.js MongoDB Driver API reference.