i trying post data mongo db through url of browser. able working using expressjs, having difficulty getting working mongodb. i'm still new this, hoping missing simple component , @ least on right track.
when enter "http://localhost:27017/api/users?id=4&token=sdfa3" or "http://localhost:27017/nodetest5/api/users?id=4&token=sdfa3" url, i'd see "4 sdfa3" on webpage. right getting webpage message: "it looks trying access mongodb on http on native driver port."
here 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 router app.use(function(req, res, next){ req.db = db; next(); }) // routes app.get('/api/users', function(req, res) { //get values url var id = req.param('id'); var token = req.param('token'); res.send(user_id + ' ' + token + ' '); }); // post localhost // parameters sent app.post('/api/users', function(req, res) { //internal db value var db = req.db; //values url var user_id = req.body.id; var token = req.body.token; //set collection var collection = db.get('usercollection'); //submit db collection.insert({ "id" : id, "token" : token }, function (err, doc){ if (err) { res.send("error encountered when trying add entry database."); } else { res.send(user_id + ' ' + token + ' '); } }); });
thank you!
the http interface mongodb can accessed via port number 28017
. you'll need provide --rest
option mongod
:
`$ mongod --rest`
you can read more in http interface documentation.
you should exercise caution when using http interface. mongodb documentation:
warning
ensure http status interface, rest api, , json api disabled in production environments prevent potential data exposure , vulnerability attackers.