Related
How do I connect to mongodb with node.js?
I have the node-mongodb-native driver.
There's apparently 0 documentation.
Is it something like this?
var mongo = require('mongodb/lib/mongodb');
var Db= new mongo.Db( dbname, new mongo.Server( 'mongolab.com', 27017, {}), {});
Where do I put the username and the password?
Also how do I insert something?
Thanks.
Per the source:
After connecting:
Db.authenticate(user, password, function(err, res) {
// callback
});
Everyone should use this source link:
http://mongodb.github.com/node-mongodb-native/contents.html
Answer to the question:
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
var db = new Db('integration_tests', new Server("127.0.0.1", 27017,
{auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});
// Establish connection to db
db.open(function(err, db) {
assert.equal(null, err);
// Add a user to the database
db.addUser('user', 'name', function(err, result) {
assert.equal(null, err);
// Authenticate
db.authenticate('user', 'name', function(err, result) {
assert.equal(true, result);
db.close();
});
});
});
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://'+DATABASEUSERNAME+':'+DATABASEPASSWORD+'#'+DATABASEHOST+':'DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
//for local server
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DATABASEHOST+':'+DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
I find using a Mongo url handy. I store the URL in an environment variable and use that to configure servers whilst the development version uses a default url with no password.
The URL has the form:
export MONGODB_DATABASE_URL=mongodb://USERNAME:PASSWORD#DBHOST:DBPORT/DBNAME
Code to connect this way:
var DATABASE_URL = process.env.MONGODB_DATABASE_URL || mongodb.DEFAULT_URL;
mongo_connect(DATABASE_URL, mongodb_server_options,
function(err, db) {
if(db && !err) {
console.log("connected to mongodb" + " " + lobby_db);
}
else if(err) {
console.log("NOT connected to mongodb " + err + " " + lobby_db);
}
});
My version:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://user:pass#dhost:port/baseName', function(err, db) {
if (err) {
console.error(err);
}
var collection = db.collection('collectionName');
collection.find().toArray(function(err, docs) {
console.log(docs);
});
});
I recommend mongoskin I just created.
var mongo = require('mongoskin');
var db = mongo.db('admin:pass#localhost/mydb?auto_reconnnect');
db.collection('mycollection').find().toArray(function(err, items){
// do something with items
});
Is mongoskin sync? Nop, it is async.
Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:
var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
assert = require('assert');
var user = 'user';
var password = 'password';
MongoClient.connect('mongodb://'+user+':'+password+'#localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
if(err){
console.log("Auth Failed");
return;
}
console.log("Connected");
db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
console.log(doc['_id']);
}
});
});
db.close();
});
This worked for me:
Db.admin().authenticate(user, password, function() {} );
You can do it like this
var db = require('mongo-lite').connect('mongodb://localhost/test')
more details ...
if you continue to have problems with the native driver, you can also check out sleepy mongoose. It's a python REST server that you can simply access with node request to get to your Mongo instance.
http://www.snailinaturtleneck.com/blog/2010/02/22/sleepy-mongoose-a-mongodb-rest-interface/
With the link provided by #mattdlockyer as reference, this worked for me:
var mongo = require('mongodb');
var server = new mongo.Server(host, port, options);
db = new mongo.Db(mydb, server, {fsync:true});
db.open(function(err, db) {
if(!err) {
console.log("Connected to database");
db.authenticate(user, password, function(err, res) {
if(!err) {
console.log("Authenticated");
} else {
console.log("Error in authentication.");
console.log(err);
}
});
} else {
console.log("Error in open().");
console.log(err);
};
});
exports.testMongo = function(req, res){
db.collection( mycollection, function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
Slight typo with Chris' answer.
Db.authenticate(user, password, function({ // callback }));
should be
Db.authenticate(user, password, function(){ // callback } );
Also depending on your mongodb configuration, you may need to connect to admin and auth there first before going to a different database. This will be the case if you don't add a user to the database you're trying to access. Then you can auth via admin and then switch db and then read or write at will.
const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myProject';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
// the following code examples can be pasted here...
return 'done.';
}
main()
//what to do next
.then(console.log)
//if there is an error
.catch(console.error)
// what to do in the end(function result won't matter here, it will execute always).
.finally(() => client.close());
you can find more in the documentation here: https://mongodb.github.io/node-mongodb-native/4.1/
I'm using Mongoose to connect to mongodb.
Install mongoose npm using following command
npm install mongoose
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/database_name', function(err){
if(err){
console.log('database not connected');
}
});
var Schema = mongoose.Schema;
var userschema = new Schema ({});
var user = mongoose.model('collection_name', userschema);
we can use the queries like this
user.find({},function(err,data){
if(err){
console.log(err);
}
console.log(data);
});
My problem is that I can enter data from my input boxes into an SQL table, but the problem is that the text from the table will not show on the page i want to. What works is that the playlist page will show the a href links depending on how many playlists i have made just not the text.
I have left out the database details for security reasons.
playlist.jade
extends layout
block content
h1= title
p Welcome to #{title}
h1 My Playlists
br
a(href='/login') Login
br
a(href='/users/createPlaylist') Create a new Playlists
br
a(href='/users/playlistCreated') test
br
for playlist, i in playlists
a(href='/users/playlistCreated') | #{playlist.text}
br
users.js
var express = require('express');
var mysql = require('mysql');
var router = express.Router();
var dbConnectionInfo = {
host : '',
user : '',
password : '',
database : 'audio_collections'
};
router.get('/createPlaylist', function(req, res, next) {
res.render('new_playlist');
});
router.get('/playlistCreated', function(req, res, next) {
res.render('name_of_created_playlist');
});
router.get('/songCreated', function(req, res, next) {
res.render('song_page');
});
router.get('/newSong', function(req, res, next) {
res.render('new_song');
});
router.post('/newPlaylist', function(req, res, next) {
var dbConnection = mysql.createConnection(dbConnectionInfo);
dbConnection.connect();
dbConnection.on('error', function(err) {
if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
// Let's just ignore this
console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
} else {
// I really should do something better here
console.log('Got a DB Error: ', err);
}
});
var playlist = {
text: req.body.thePlaylist
};
dbConnection.query('INSERT INTO Playlists (playlist_name) VALUES(?)', [playlist.text], function(err, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
if (err) {
throw err;
}
// notice that results.insertId will give you the value of the AI (auto-increment) field
playlist.id = results.insertId;
// Going to convert my joke object to a JSON string a print it out to the console
console.log(JSON.stringify(playlist));
// Close the connection and make sure you do it BEFORE you redirect
dbConnection.end();
res.redirect('/');
});
router.post('/newSongAdded', function(req, res, next) {
var dbConnection = mysql.createConnection(dbConnectionInfo);
dbConnection.connect();
dbConnection.on('error', function(err) {
if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
// Let's just ignore this
console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
} else {
// I really should do something better here
console.log('Got a DB Error: ', err);
}
});
var song = {
text: req.body.theSong,
url: req.body.theSongURL
};
dbConnection.query('INSERT INTO Songs (song_name, song_url) VALUES(?,?)',[song.text, song.url], function(err, results,fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
if (err) {
throw err;
}
// notice that results.insertId will give you the value of the AI (auto-increment) field
song.id = results.insertId;
// Going to convert my joke object to a JSON string a print it out to the console
console.log(JSON.stringify(song));
// Close the connection and make sure you do it BEFORE you redirect
dbConnection.end();
res.redirect('/');
});
});
});
module.exports = router;
index.js
var express = require('express');
var mysql = require('mysql');
var router = express.Router();
var dbConnectionInfo = {
host : '',
user : '',
password : '',
database : 'audio_collections'
};
/* GET home page. */
router.get('/login', function(req, res, next) {
res.render('login');
});
router.post('/login', function(req, res, next) {
var username = req.body.username;
username = username.trim();
if (username.length == 0) {
res.redirect('/login');
}
else {
req.session.username = username;
res.redirect('/');
}
});
router.get('/', function(req, res, next) {
var dbConnection = mysql.createConnection(dbConnectionInfo);
dbConnection.connect();
dbConnection.on('error', function(err) {
if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
// Let's just ignore this
console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
} else {
// I really should do something better here
console.log('Got a DB Error: ', err);
}
});
dbConnection.query('SELECT * FROM Playlists', function(err, results, fields){
if (err) {
throw err;
}
var allPlaylists = new Array();
for (var i = 0; i < results.length; i++) {
var playlist = {
id: results[i].id,
text: results[i].text
};
console.log(JSON.stringify(playlist));
allPlaylists.push(playlist);
}
dbConnection.end();
res.render('playlists', {playlists: allPlaylists});
});
router.get('/users/playlistCreated', function(req, res, next) {
var dbConnection = mysql.createConnection(dbConnectionInfo);
dbConnection.connect();
dbConnection.on('error', function(err) {
if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
// Let's just ignore this
console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
} else {
// I really should do something better here
console.log('Got a DB Error: ', err);
}
});
dbConnection.query('SELECT * FROM Songs', function(err, results, fields){
if (err) {
throw err;
}
var allSongs = new Array();
for (var i = 0; i < results.length; i++) {
var song = {};
song.id = results[i].id;
song.text = results[i].text;
song.url = results[i].url;
console.log(JSON.stringify(song));
allSongs.push(song);
}
dbConnection.end();
res.render('name_of_created_playlist', {songs: allSongs});
});
});
});
module.exports = router;
new_playlist.jade
extends layout
block content
form(method='POST', action='/users/newPlaylist')
div
label(for='thePlaylist') Name of Playlist
div
textarea(type='text', name='thePlaylist')
br
input(type='submit', name='Add new Playlist')
a(href='/') Cancel
Here is the database and table setups
database and table setup
I would really appreciate the help and I have been stuck on this for a week now.
Got it fixed I didnt need the for loops inside my array
Only needed var allPlaylist = results; Since results is an array already
I have successfully set up a database using mongodb, and I have managed to add new entries to my collection. However, when I use a similar method to delete, nothing happens.
Express.js code
router.post('/deleteproject', function(req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/plugd';
MongoClient.connect(url, function(err, db) {
if (err) {
console.log("Unable to connect to server", err);
} else {
console.log('Connected to server');
var collection = db.collection('projects');
collection.remove(
{_id: new mongodb.ObjectID(req.body)}, function(err, result) {
if (err) {
console.log(err);
} else {
res.redirect("thelist");
}
db.close();
});
}
});
});
Jade code
h2.
ul
Projects
each project, i in projectlist
#project_list_item
a(href='#') #{project.owner} - #{project.project}
p #{project.ref1}
p #{project.ref2}
p #{project.ref3}
form#form_delete_project(name="deleteproject", method="post", action="/deleteproject")
input#input_name(type="hidden", placeholder="", name="_id", value="#{project._id}")
button#submit_project(type="submit") delete
I figured it out. Here is my fix for deleting data from a mongodb collection using a router in express.js.
Express.js
router.post('/deleteproject', function(req, res) {
var MongoClient = mongodb.MongoClient;
var ObjectId = require('mongodb').ObjectId;
var url = 'mongodb://localhost:27017/app';
MongoClient.connect(url, function(err, db) {
if (err){
console.log('Unable to connect to server', err);
} else {
console.log("Connection Established");
var collection = db.collection('projects');
collection.remove({_id: new ObjectId(req.body._id)}, function(err, result) {
if (err) {
console.log(err);
} else {
res.redirect("thelist");
}
db.close();
});
}
});
});
Jade code
extends layout
block content
h2.
Projects
ul
each project, i in projectlist
#project_list_item
a(href='#') #{project.owner} - #{project.project}
p #{project.ref1}
p #{project.ref2}
p #{project.ref3}
form#form_delete_project(name="deleteproject", method="post", action="/deleteproject")
input#input_name(type="hidden", placeholder="", name="_id", value="#{project._id}")
button#submit_project(type="submit") delete
The jade file is rendering to a page called 'thelist' that lists each item in the collection.
The form section handles the delete function for each item in the list.
This works for me as long as I keep Jade's indents happy :)
Try this and see if it works :
router.post('/deleteproject', function(req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/plugd';
MongoClient.connect(url, function(err, db) {
if (err) {
console.log("Unable to connect to server", err);
} else {
console.log('Connected to server');
var collection = db.collection('projects');
collection.remove(
{_id: req.body}, function(err, result) {
if (err) {
console.log(err);
} else {
res.redirect("thelist");
}
db.close();
});
}
});
});
Since you're on MongoDB's Node.js Native Driver, you don't need to marshall _id inside ObjectId. You can directly specify the _id as string
So, I'm new to all this and was developing a login and registration page. I can easily save the data to the database while registering through registration page, but the problem is I don't know what to do during login page. What type of statements do I have to use to match the entered email address with the email addresses of each document in the "employee" collection, and then check if the password is correctly entered.
Here is my express file main.js:
var express = require("express");
var app = express();
var connection = require("../connection");
module.exports = function(app){
app.get('/', function(req, res){
res.render("login.html");
});
app.get('/adduser', function(req, res){
res.render("login.html");
var name = req.param('name');
var email = req.param('email');
var employeeid = req.param('employeeid');
var password = req.param('password');
var position='';
var joining_date= '';
var active= 'Y';
console.log("Name: " + name + " Email: " + email + "Employee id: " +employeeid);
connection.add(name,email,employeeid,password,position,joining_date,active);
});
//CHECKING IF MAIL AND PASSWORD MATCHES
app.get('/checkuser', function(req, res){
var email = req.param('email');
var password = req.param('password');
console.log(" Email: " + email);
connection.check(email,password);
});
And this is the connection file, connection.js:
var add=function(uname,uemail,uemployeeid,upassword,uposition,ujoining_date,uactive) {
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('employees');
//Create some users
var data = {name:uname,email:uemail,employeeid:uemployeeid,password:upassword,position:uposition,joining_date:ujoining_date,active:uactive };
/* var user2 = {name: 'modulus user', age: 22, roles: ['user']};
var user3 = {name: 'modulus super admin', age: 92, roles: ['super-admin', 'admin', 'moderator', 'user']};*/
// Insert some users
collection.insert(data, function (err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "employees" collection. The documents inserted with "_id" are:', result.length, result);
}
db.close();
});
}
});
} //NOW CHECKING IF ENTERED EMAIL AND PASS MATCHES OR EMAIL EXISTS???
var check= function(uemail,upassword)
{
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
var collection = db.collection('employees');
collection.findOne({uemail:uemail}, function(err,doc){ //I HAVE NO IDEA WHAT TO DO HERE??
if(err) throw err;
if(doc)
console.log("Found: "+uemail+", pass=");
else
console.log("Not found: "+uemail);
db.close();
});
}
});
}
module.exports.add=add;
module.exports.check=check;
EDITED: THE FIX FOR THE ABOVE PROBLEM IS PROVIDED BY GMANIC BELOW..
Here is the fix, you are trying to match on uemail but you saved it as email. You could even take it a step further and match on the password at the same time.
exports.check = function(uemail, upassword)
{
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
var collection = db.collection('employees');
collection.findOne({ email: uemail, password: upassword }, function(err, doc){
if(err) throw err;
if(doc) {
console.log("Found: " + uemail + ", pass=" + upassword);
} else {
console.log("Not found: " + uemail);
}
db.close();
});
}
});
}
There are some best practices that you should add in, but to answer your question this should work.
How do I programmatically create a database using the MongoDB Node.JS driver?
This looks promising, but I'm not sure how to connect to with the admin credentials and create a new database.
var db = new Db('test', new Server('locahost', 27017));
// Establish connection to db
db.open(function(err, db) {
assert.equal(null, err);
// Add a user to the database
db.addUser('user3', 'name', function(err, result) {
assert.equal(null, err);
// Authenticate
db.authenticate('user3', 'name', function(err, result) {
assert.equal(true, result);
// Logout the db
db.logout(function(err, result) {
assert.equal(true, result);
// Remove the user
db.removeUser('user3', function(err, result) {
assert.equal(true, result);
db.close();
});
});
});
});
});
in mongodb databases and collections are created on first access. When the new user first connects and touches their data, their database will get created then.
This seems to work.
var Db = require('mongodb').Db,
Server = require('mongodb').Server;
var db = new Db('test', new Server('localhost', 27017));
db.open(function (err, db) {
if (err) throw err;
// Use the admin database for the operation
var adminDb = db.admin();
adminDb.authenticate('adminLogin', 'adminPwd', function (err, result) {
db.addUser('userLogin', 'userPwd', function (err, result) {
console.log(err, result);
});
});
});
Try as below:
var adminuser = "admin";
var adminpass = "admin";
var server = "localhost";
var port = 27017;
var dbName = "mydatabase";
var mongodb = require('mongodb');
var mongoClient = mongodb.MongoClient;
var connString = "mongodb://"+adminuser+":"+adminpass+"#"+server+":"+port+"/"+dbName;
mongoClient.connect(connString, function(err, db) {
if(!err) {
console.log("\nMongo DB connected\n");
}
else{
console.log("Mongo DB could not be connected");
process.exit(0);
}
});