I am building a nodejs app using expressjs framework. I would like to ask how do we connect to mongodb using monk? i found this code online however it seems that we do not need to specify username and password. why is that so?
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
Appreciate any advice.
There are two methods of passing username/password:
// first:
var db = monk('USERNAME:PASSWORD#localhost:27017/nodetest1');
// second:
var db = monk('localhost:27017/nodetest1', {
username : 'USERNAME',
password : 'PASSWORD'
});
It's not very well documented, but since monk uses mongoskin, you can look here for more information.
I want to add an alternative to the answers above as neither worked for me.
So the way I was able to connect to a mongod --auth instance was:
1.Make sure you create a user while logged into mongodb as a user with appropriate permissions to create users on databases (like a user with the role userAdminAnyDatabase). If you don't have a user with this role restart mongo with just mongod without --auth and login as your superuser (if you have one) or with a simple mongo command and make this user with the appropriate privileges.
I highly recommend reading up on mongodb roles here: http://docs.mongodb.org/manual/reference/built-in-roles/
2.Once you are logged into your database instance with the appropriate user who is supposed to be creating other users, type use db_name where db_name is the name of your database that you want to make the user for.
3.Once inside this database use the db.createUser command like so: db.createUser({user:"your_username", pwd:"your_password", roles:["your_role"]})
It's documented here: http://docs.mongodb.org/manual/reference/method/db.createUser/
4.Then just use db = monk('USERNAME:PASSWORD#localhost:27017/DATABASE_NAME') in your code.
After you've done this you should be able to log into a running mongod --auth instance with a user for the particular database you created that user for.
For anyone curious I'm developing a little web app in Koa. Using monk and co-monk.
In apps.js:
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/ta');
module.exports = db;
In /lib/mylib.js:
var db = require('../apps.js')
Though i would recommend making a separate file called db.js and in that file export the connection ,that is more cleaner.
Related
I am working on a project that requires a dedicated database per registered user. I prefer working with MongoDB so I'm using that for the same (Am I Right?). The app uses a REST API as the backend (written in Node Express) and an AngularJS App. So, what I think of doing is whenever a user makes a request to some API endpoint say, a GET request to api/user/mydata, I would create a connection to his particular database, fetch the required data, close the connection and return the fetched data as the response. Is this approach correct? Also, I'm using Mongoose as the ODM and PassportJS for user Authentication. Moreover, users of my app are mutually exclusive. There is no data connection between a user with any other registered user.
There's a way to do that but only without using Mongoose. You would have to create a root connection to your MongoDB server (mind it, not to a particular database on that server) using the mongodb node module and then you can switch between the database as per your query requirement without creating a new connection per database as shown below:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// URL to the root of MongoDB Server and not a particular db
const url = 'mongodb://localhost:27017';
// Database Names
const dbName1 = 'myproject1';
const dbName2 = 'myproject2';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db1 = client.db(dbName1);
const db2 = client.db(dbName2);
client.close();
});
You can't do this through mongoose, as mongoose and its models require connection to be made to a particular database and not to just the root db server. Anyways, I didn't want to give up mongoose for my own project so I just had to resort to initializing the db connection and its models per HTTP request by the user and closing the connection upon response.
I have a user with the role: {role: 'root', db:'admin'} which should have access to all the databases in my mongo instance. I'm using mongoskin in node.js to interact with mongo. My problem is that it isn't correctly accessing my databases. If I authenticate with
mongodb://owner:mylocalpassword#localhost:27017/mydatabase
It simply gives me MongoError: Authentication failed. If I instead auth with:
mongodb://owner:mylocalpassword#localhost:27017/admin
it authenticates, but I can't access mydatabase.
Here's my connection code:
var connection = mongoskin.db("mongodb://owner:mylocalpassword#localhost:27017/admin", {journal:true, auto_reconnect:true})
I assume that since I'm accessing the admin database there, that's the only one it interacts with. So I tried do then do this:
var mydatabaseConnection = connection.db('mydatabase')
But when I use that, my app is returning no results for queries on collections that I know have data. What am I doing wrong here? How do I get this user to access a database other than admin?
Ok, so I found out that mongoskin's db method simply doesn't work. Finally I'm forced to completely remove mongoskin from my codebase. The real answer here is don't use mongoskin.
This code worked with mongo native:
MongoClient.connect("mongodb://owner:mylocalpassword#localhost:27017/admin", {journal: true, auto_reconnect:true}).then(function(db) {
console.log("Connected!")
var mydb = db.db('mydatabase')
var User = mydb.collection('User')
return User.find({}).toArray().then(function(users) {
console.log(users)
db.close()
})
}).catch(function(e) {
console.log(e.stack)
})
I'm using express-session along with passport and MongoStore to store my sessions. They're obviously being stored in the MongoDB, how can I access them just to take a look at? There's no business value in this it's just from a theoretical/technical perspective that I'm interested, thanks!
Run mongo shell with command:
mongo
Create a new connection:
conn = new Mongo()
Access your DB:
db = conn.getDB('myDB')
This command displays the sessions (inside the inprog array, look at the objects with client):
db.currentOP(true)
I have an express app that connects to MongoDB via mongoose, and I also have an init script that will occasionally connect to MongoDB.
Is there any way to detect if there is an existing connection to the DB, so I will not need to connect again in the script anytime I want to run it, also is there any consequences for connecting to the DB multiple times via mongoose.
you can check this using mongoose.connection.readyState,
ex.
var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);
The state would return 1 if already connected.
You can check the readyState
var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);
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.