I'm trying to display mongodb data in my html page. I've already managed to insert data in db but for some reason my "get" function does not work.
I'm using node.js with express framework and Angular for front-end and routing.
This is my "get" function to retreive data from MongoDB:
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/loodgieters';
router.get('/get-data', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('user-data').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function(){
db.close();
res.render('index', {items: resultArray});
});
});
});
And my "post" which works
router.post('/insert', function(req, res, next) {
var item = {
name: req.body.name,
adress: req.body.adress,
postal: req.body.postal,
city: req.body.city,
email: req.body.email,
phone: req.body.phone,
quotation: req.body.quotation,
message: req.body.message
};
mongo.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('user-data').insertOne(item, function(err, result){
assert.equal(null, err);
console.log('Item inserted');
db.close();
});
});
res.redirect('/contact');
});
i am not sure if this is the correct way to open and close mongo connection each time you are trying to query .
if you want to go for another approach then use mongoose
and follow something like this
https://pastebin.com/g7aatzzj
I think that you have a mistake in your .find().forEach function callbacks. The error handling seems to be in the endCallback not the iteratorCallback.
According to the official doc, the correct way should be :
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/loodgieters';
router.get('/get-data', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('user-data').find({});
cursor.forEach(function(doc){
assert.notEqual(null, doc);
resultArray.push(doc);
}, function(err, doc){
assert.equal(null, err);
db.close();
res.render('index', {items: resultArray});
});
});
});
This can also be found in their unit tests
var cursor = collection.find({})
.map(function(x) { return {a:1}; })
.batchSize(5)
.limit(10);
cursor.forEach(function(doc) {
test.equal(1, doc.a);
}, function(err, doc) {
test.equal(null, err);
db.close();
test.done();
});
I think that you must have a error that is not passed to the first callback and not handled in the second one. So you do not see the error.
Try to insert an empty object to the find() function as following:
var cursor = db.collection('user-data').find({});
I have just run your code and modified it a bit for my purposes.
Please find the following snippet
//Instantiate MongoClient
var mongo = require('mongodb').MongoClient;
//Assert library (Perhaps overkill if you are writing production-level code)
var assert = require('assert');
//Express engine
var express = require('express');
//URL for my mongo instance
//Connecting to the blog database
var url = 'mongodb://localhost:27017/blog';
//Instantiate express
var router = express();
//Get operation
router.get('/get', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('posts').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function(){
db.close();
//I have no index file to render, so I print the result to console
//Also send back the JSON string bare through the channel
console.log(resultArray);
res.send(resultArray);
});
});
});
//Start listeninig
//Hardcoded port 1000
var server = router.listen(1000, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Content Provider Service listening at http://%s:%s", host, port);
});
Therefore to get this working for you:
Change the url to 'mongodb://localhost:27017/loodgieters';
Change router to '/get-data'
I hope this helps!
Also consider using splitting the implementation of the get operation to another module to help for the Separation of Responsibilities to make your code more robust.
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);
});
I am trying to write a REST backend using Node.js, express and MongoDB but am having some issues creating PUT calls for some reason. The issue is with app.post('/contacts/add', contacts.addContacts) as it works fine if I change it to GET but when I change it to either PUT or POST I get the error Cannot GET /contacts/add Any ideas?
I am using express 4.15.3, mongodb 3.4.5 and npm 4.2.0
server.js:
var express = require('express'),
contacts = require('./routes/contacts');
bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/contacts/chalkboard/:id', contacts.getChalkboardContacts);
app.get('/contacts/get/:uid', contacts.getContacts);
app.post('/contacts/add', contacts.addContacts);
app.listen(3000);
console.log('Listening on port 3000...');
contacts.js
var mongo = require('mongodb');
mongo.BSONPure = require('bson').BSONPure;
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('db', server);
db.open(function(err, db) {
if(!err) {
console.log("Connected to database");
db.collection('contacts', {strict:true}, function(err, collection) {
if (err) {
console.log("The 'contacts' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
exports.getChalkboardContacts = function(req, res) {
var uid = req.params.uid.toString();
var date = new Date();
var timeInMs = date.getMilliseconds();
console.log(uid);
db.collection('contacts', function(err, collection) {
console.log('collection: ' + collection);
collection.find({uid: uid, lastMessage: {$gte: timeInMs}}).toArray(function(err, items) {
res.send(items);
});
});
};
exports.getContacts = function(req, res) {
var uid = req.params.uid.toString();
console.log(uid);
db.collection('contacts', function(err, collection) {
console.log('collection: ' + collection);
collection.find({uid: uid}).toArray(function(err, items) {
res.send(items);
});
});
};
exports.addContacts = function(req, res) {
console.log('working');
db.collection('contacts', function(err, collection) {
var id = "592159bc3e48764418170399";
var contact = {uid: "592159bc3e48764418173333",
keyUid: "592159bc3e48764418171444",
name: "Billy Jean",
phoneNumber: "+491721894733",
battery: "47%", longitude: "0",
latitude: "0",
city: "city",
country: "country",
place: "place",
address: "address",
lastMessage: "lastMessage",
lastUpdated: "lastUpdated"};
collection.update({'uid':id}, {$push:{'contacts':contact}}, function(err, result) {
if (err) {
console.log('Error updating contact: ' + err);
res.send({'error':'An error has occurred'});
} else {
console.log('' + result + ' document(s) updated');
res.send(result);
}
});
});
};
I didn't spot anything immediately wrong with the code.
You might be falling into a very common pitfall when using body-parser for JSON. Your request must specify Content-Type: application/json in the request for the parser to parse it. Otherwise, it won't work.
If that doesn't do the trick, if you can share any error messages or response codes you get, it may illuminate another issue.
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
I'm attempting to create a Rest API using Node.js, Express, and MongoDB. I am currently running on my local host :3000. When I try to restart and run the server I am using the route http://localhost:3000/drinks
I use Postman to send HTTP requests.
https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en
While trying to send the route above, it does not retrieve any information. It just continues load.
This is my first time creating a REST API and I'm not sure why it isn't retrieving the data. Attached below is my code. Thanks in advance!
server.js
var express = require('express'),
drink = require('./routes/drinks');
var app = express();
app.configure(function () {
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
});
app.get('/drinks', drink.findAll);
app.get('/drinks/:id', drink.findById);
app.listen(3000);
console.log('Listening on port 3000...');
drinks.js
var mongo = require('mongodb');
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('drinkdb', server);
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'drinkdb' database");
db.collection('drinks', {strict:true}, function(err, collection) {
if (err) {
console.log("The 'drinks' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving drink: ' + id);
db.collection('drinks', function(err, collection) {
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
res.send(item);
});
});
};
exports.findAll = function(req, res) {
db.collection('drinks', function(err, collection) {
collection.find().toArray(function(err, drinks) {
res.send(drinks);
});
});
};
/*---------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
// You'd typically not find this code in a real-life app, since the database would already exist.
var populateDB = function() {
var drinks = [
{
id: "1",
name: "Margarita",
ingredients: ["Tequila","Lime juice","Triple Sec","Lime","Salt","Ice"],
measurements: ["2 oz","1 oz","1 oz","1","optional","optional"],
directions: "Shake the other ingredients with ice, then carefully pour into the glass. Served: On the roc\
ks; poured over ice. Optional: Salt the rim of the glass by rubbing lime on it so it sticks."
},
{
id: "2",
name: "Strawberry Margarita",
ingredients: ["Tequila", "Lime juice","Triple Sec","Strawberries","Lime","Salt", "Ice"],
measurements: ["2 oz","1 oz", "1 oz", "3 1/2 cups", "1", "optional", "optional"],
directions: "Combine strawberries, ice, tequila, lime juice, and triple sec in a blender, and process unt\
il the mixture is smooth. Carefully pour into the glass. Served: On the rocks; poured over ice. Optional: Salt the ri\
m of the glass by rubbing lime on it so it sticks."
}];
db.collection('drinks', function(err, collection) {
collection.insert(drinks, {safe:true}, function(err, result) {});
});
};
Warnings are:
express deprecated app.configure: Check app.get('env') in an if statement server.js:6:5
connect deprecated multipart: use parser (multiparty, busboy, formidable) npm module instead node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:56:20
connect deprecated limit: Restrict request size at location of read node_modules/express/node_modules/connect/lib/middleware/multipart.js:86:15
I think Ashley is on the right track. But to make it more clear where the problem is happening try using this as a guide:
http://expressjs.com/en/guide/routing.html
app.get('/drinks', function (req, res) {
drink.findAll(req, res);
});
Then you can add logging in between this call and in your findAll function.
Your models (drinks.js) accept two parameters (req & res) but on your route you don't pass in any parameters.
Try the following:
app.get('/drinks', function(req, res) {
drink.findAll(req, res);
});
app.get('/drinks/:id', function(req, res){
drink.findById(req, res);
});
Alternatively, you could achieve the same with a callback based structure:
server.js
...
app.get('/drinks', function(req, res) {
drink.findAll(function(err, drinks){
res.send(drinks)
});
});
...
drinks.js
...
exports.findAll = function(callback) {
db.collection('drinks', function(err, collection) {
collection.find().toArray(function(err, drinks) {
callback(err, drinks)
});
});
};
(error handling required)
...
I have a MongoDB connect call that crashes a heroku app..
I have been editing what was originally localHost code (was working perfectly) to work with Heroku MongoDb addons (like MongoLab), but how do I get someDBcollectionVariable to work with someDBcollectionVariable.find()
//MongoDB
var mongodb = require('mongodb');
var db;
var MONGODB_URI = process.env.MONGOLAB_URI;
var PORT = process.env.PORT;
var testColl;
function dbConnect() {
return mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
if(err) throw err;
db = database;
var testColl = db.collection('test');
app.listen(PORT);
console.log('Listening on port ' + PORT);
return testColl;
});
}
//calls then look like
app.post('/add', function (req, res) {
testColl.insert(
{
"title" : req.body.title,
"quantity" : parseInt(req.body.quantity)
},
function (err, doc) {
getAll(res);
});
});
//and getAll looks like this
function getAll(res) {
testColl.find().sort( { value: 1 } ).toArray(function (err, docs) {
res.json({docs: docs});
});
}
Before moving that code inside dbConnect(), testColl.find.. was generating a ResponseError because the connect code was completing before the variable could be set?
Returning a value from an asynchronous function makes no sense. To use the a value, you need to pass it to a callback function. The same goes for errors (you can't throw asynchronously). A fixed version of your code could look like:
//MongoDB
var mongodb = require('mongodb');
var db;
var MONGODB_URI = process.env.MONGOLAB_URI;
var PORT = process.env.PORT;
var testColl;
function dbConnect(callback) {
mongodb.MongoClient.connect(MONGODB_URI, function (err, database) {
if (err) {
return callback(err);
}
db = database;
database.collection('test', function (err, testColl) {
if (err) {
return callback(err);
}
app.listen(PORT);
console.log('Listening on port ' + PORT);
callback(null, testColl);
});
});
}
//calls then look like
dbConnect(function (err, testColl) {
if (err) {
return console.error(err.stack || err.message);
}
testColl.find...
});