How to add MongoDB Atlas cloud database in KeystoneJS v5 - node.js

I have database server on MongoDB Atlas Cloud.
I can Setup Keystonejs 5 with MongoDB local database but I don't to what Keystonejs expect for database connection string and settings.
below detail may useful to understand my issue
Mongoose Database Adapter
Usage
const { MongooseAdapter } = require('#keystonejs/adapter-mongoose');
const keystone = new Keystone({
name: 'My Awesome Project',
adapter: new MongooseAdapter(),
});
API new MongooseAdapter(options)
options.mongoUri (optional)
This is used as the uri parameter for mongoose.connect().
Default: Environmental variable (see below) or 'mongodb://localhost/<DATABASE_NAME>'
If not specified, KeystoneJS will first look for one of the following environmental variables:
CONNECT_TO,
DATABASE_URL,
MONGO_URI,
MONGODB_URI,
MONGO_URL,
MONGODB_URL,
MONGOLAB_URI,
MONGOLAB_URL
If none of these are found a connection string is derived with a DATABASE_NAME from the KeystoneJS project name.
Mongoose Options (optional)
Additional Mongoose config options are passed directly through to mongoose.connect().
See the Mongoose docs for a detailed list of options.

You just need to add an environment variable that matches one of the ones listed in the question and then set that environment variable to be the connection string that MongoDB atlas cloud gives you.
I added a .env file to my project and then added an entry for MONGO_URI there, then used the dotenv package.

You can do it by adding .env file or you can directly pass mongoUri to adapter.
See the code below:
const keystone = new Keystone({
name: 'My Awesome Project',
adapter: new MongooseAdapter({mongoUri:"mongodb+srv://....."}),
});

Related

Configure Enviroment Variables For Production Node.JS

I am trying to deploy my test Express.js app on Heroku using GitHub for resources and mlab for my database. In development th app doesn't have problems when I pass mLab connection string but in production... How must my production environment look?
Here is my config.js:
const env=require('dotenv').config();
module.exports = {
development: {
port: process.env.PORT|| 3000,
dbPath: process.env.DB_CONNECTION,
},
production: {
port: process.env.PORT|| 3000,
dbPath: process.env.DB_CONNECTION_MLAB,
}
};
Your .env file probably isn't (and shouldn't be) used in production. It should be ignored in your Git repository.
This means your production database configuration needs to come from somewhere else. If you're using the official mLab addon you can access your connection string via the MONGODB_URI environment variable, which the addon sets automatically.
If you're not using the official addon you should set the appropriate environment variable yourself, e.g. via
heroku config:set MONGODB_URI=...
In either case, make sure the name of the environment variable in your code matches what's set in the environment. Generally there is no need for separate development and production variables since they are set in different environments. I recommend using MONGODB_URI everywhere.

winston-mongodb error after initializing

I'm trying to configure a basic winston logger but keep getting the same error.
All I have so far to configure it is this
var winston = require('winston');
var mongoLog = require('winston-mongodb').MongoDB;
var appSettings = require('./appSettings');
var logger = new (winston.Logger)();
logger.add(mongoLog, {
db: appSettings.database,
host: appSettings.dbConnection,
collection: appSettings.loggingCollection
}
);
This is the error I'm getting.
winston-mongodb: error initialising logger Error: invalid schema, expected mongodb
The host is the ip of a mongodb instance in azure, but that doesn't seem to be the issue because if I remove host (defaulting it to localhost according to the docs) and try to have it connect to my local mongo instance it gives the same error. It also doesn't seem to matter if I call any methods on the logger or not.
Was looking at the wrong documentation I guess?
On this page it has the db param described like this
db: The name of the database you want to log to.
So I thought I would have the db name there and would need to specify the host separately.
But on this page it has a different description.
db: MongoDB connection uri, pre-connected db object or promise object which will be resolved with pre-connected db object.
Which apparently was the correct description, the full URI being this format:
mongodb://<host>:<port>/<db>

What is the correct URL schema for connecting to mongodb with multiple databases

Setting up a new project, I wanted to have separate databases for test, dev and prod:
d:/mongodb/project/test
d:/mongodb/project/dev
d:/mongodb/project/prod
I got these up with mongod --dbpath d:/monodb/project/<env>
When I try to connect I get Error: More than 1 database name in URL
const { MongoClient } = require('mongodb')
MongoClient.connect('mongodb://localhost:27017/project/dev')
The example given in the api docs doesn't help much
var MongoClient = require('mongodb').MongoClient,
test = require('assert');
// Connection url
var url = 'mongodb://localhost:27017/test';
// Connect using MongoClient
MongoClient.connect(url, function(err, db) {
What is the correct specification for the url connection? (Or, if I am going about this the wrong way entirely, what is the best way to separate databases for testing?)
You can connect to mongodb using this driver as instructed in their documentation:
http://mongodb.github.io/node-mongodb-native/2.2/quick-start/quick-start/
So the URL you have there is correct.
If you want to have separate databases (which could also be on different hosts with different credentials) then I suggest you use a config package:
https://www.npmjs.com/package/config
This allows you to define a configuration for each environment where default will be a catch all if environment variable cannot be matched to a json file. In other words, NODE_ENV=prod would map to prod.json, NODE_ENV=test would map to test.json and NODE_ENV=[empty] would map to default.json. This is one possible setup.
You definitely don't want to create multiple connections for each environment. This is not necessary.

Strongloop: setup Storage Component for Amazon S3

I'm new to Node.js and Loopback. I have been using Deployd so far and I'm trying to migrate to Loopback. The S3 bucket module on Deployd was working great.
So...:
I'm on this website https://github.com/strongloop/loopback-component-storage
I run, in my project folder,
npm install loopback-component-storage
I then need to create a datasource.
To setup the new datasource, I tried
slc loopback:datasource
It doesn't provide me with the option to create a source that is a storage. So I rule that option out I guess
I see there is this piece of code on the github (link above):
var ds = loopback.createDataSource({
connector: require('loopback-component-storage'),
provider: 'filesystem',
root: path.join(__dirname, 'storage')
});
var container = ds.createModel('container');
app.model(container);
I guess this is the right way to create a datasource, but where do I place this code and how do I execute it?
How do I adapt this code to work with Amazon?
{ provider: 'amazon', key: '...', keyId: '...' }
I suppose key is my secret key and keyId my access key id, but can you confirm?
I'm just having trouble getting started... thanks for your help in advance
Where to put the code: https://github.com/strongloop/loopback-component-storage/blob/master/example/app.js
tl;dr, just put it in app.js (1.x structure) or server/server.js (2.x structure)
This example I linked to is using the old LoopBack 1.x structure. I will be updating that example in the coming weeks to use the new LoopBack 2.x structure.
Amazon provider example: http://docs.strongloop.com/display/LB/Storage+service
You can add a datasource manually in server/datasources.json too. This way, you should be able to create a container model using the storage data source.
To do this by code as you illustrated, you can either modify server/server.js or drop a JS file into server/boot with an exported function as:
module.exports = function(app) {
// your code
};
Thanks #Raymond, I took the second option.
I created file server/boot/xyz.js and put this in there:
module.exports = function(server) {
var path = require('path');
var ds = server.loopback.createDataSource({
connector: require('loopback-component-storage'),
provider: 'filesystem',
root: path.join(__dirname, '../../storage')
});
var container = ds.createModel('container');
server.model(container);
};
I cannot see the model in the explorer but I can call the service with:
http://localhost:3000/api/containers

How to use MongoDB with mean.io

I am new to server side javascipt. I have started with mean.io. I gained some understanding of nodejs, express, mongodb last few days. I have my mean.io app but I don't know what's the right way to connect to mongodb and query it from my js files.
Is there a guide/blog which can help me work with mongodb from my server side javascript files?
All I want is to store some data mongodb and fetch that at some later point.
By default, you should see there is a mean-dev collection in your mongodb. The best way I thought to get familiar with mongo and mean is play around the code (for instance, the article package). Inside /packages/article/system/, you will see how the blog example works.
That works great for me.
I couldn't find one related to mean.io but below few links helped me get started with mean.io.
http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/
https://www.youtube.com/watch?v=AEE7DY2AYvI
https://www.youtube.com/watch?v=5e1NEdfs4is
Edit:
Past few days I have been working on it and by test & learn I was able to got things working for me. I'll share whatever I know till now.
So mean.io use mongoose ODM to connect to the mongodb.
mean.io would automatically connect to your DB. You can configure DB name in development.js db: 'mongodb://localhost/myDB'. So you won't have to worry about connecting to mongoDB. You just need to start the mongoDB using mongod.
How to use mongoose?
To use mongoose to connect to mongoDB you need to build schemas. You can do so in myApp/app/models directory, since they represents models.
Sample model file user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: String,
email: String,
DOB : Date,
address: {
house_no: String,
street: String
}
});
module.exports = mongoose.model('tbl_user',userSchema);
Note:- tbl_user would be stored as tbl_userS in DB.
How to save data to mongoDB?
One would generally do save to DB in controller. Below I have shown how one can do this.
To make models available to all controller one need to write this piece of code in server.js so that all your models get registered during server startup. Alternatively, import individual models using require('tbl_user').
Server.js :-
var models_path = __dirname + '/app/models';
var arrFiles = fs.readdirSync(models_path);
arrFiles.forEach(function(file){
if(file.indexOf('.js') > 0){
require(models_path + '/' + file);
}
});
controller code myApp/app/controllers/myController.js
var mongoose = require('mongoose');
var jsonEntry = {'name':'Mady', 'email':'xyz#xyz.com', 'address':{'house_no':12N, 'stree':'abc'}};
var User = mongoose.model('tbl_user');
var user = new User(jsonEntry);
user.save();
The above code would create and update the tbl_users collection in mongoDB.

Resources