I am trying to post data to a mongo DB through a URL of a browser. I was able to get it working using only expressJS, but I am having difficulty getting it working with mongodb. I'm still very new to this, so I am hoping that I am just missing a simple component and that I am at least on the right track.
When I enter "http://localhost:27017/api/users?id=4&token=sdfa3" or "http://localhost:27017/nodetest5/api/users?id=4&token=sdfa3" into the url, I'd like to see "4 sdfa3" on the webpage. Right now I am just getting a webpage with the message: "It looks like you are trying to access MongoDB over HTTP on the native driver port."
Here is my server.js file:
// packages
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var app = express();
var bodyParser = require('body-parser');
//db stuff
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest5');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded
//make accessible mongo db accessible to router
app.use(function(req, res, next){
req.db = db;
next();
})
// routes
app.get('/api/users', function(req, res) {
//get values from URL
var id = req.param('id');
var token = req.param('token');
res.send(user_id + ' ' + token + ' ');
});
// POST to localhost
// parameters sent with
app.post('/api/users', function(req, res) {
//internal DB value
var db = req.db;
//values from URL
var user_id = req.body.id;
var token = req.body.token;
//set collection
var collection = db.get('usercollection');
//Submit to DB
collection.insert({
"id" : id,
"token" : token
}, function (err, doc){
if (err) {
res.send("Error encountered when trying to add entry to database.");
}
else {
res.send(user_id + ' ' + token + ' ');
}
});
});
Thank you!