12-23 19:35
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[Web App/Node.js Express] 웹 브라우저 주소창의 쿼리를 이용한 도큐먼트 저장 본문

Programming/Web App

[Web App/Node.js Express] 웹 브라우저 주소창의 쿼리를 이용한 도큐먼트 저장

cinema4dr12 2015. 4. 19. 23:55

 Express를 이용하여 웹 브라우저에서 입력한 쿼리를 MongoDB에 입력하는 방법에 대해 알아본다.


[app.js]

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var routes = require('./routes/index');
var users = require('./routes/users');
var posts = require('./routes/posts');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');

// port setup
app.set('port', process.env.PORT || 3000);

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);
app.use('/posts', posts);

// mongoose
var uri = 'mongodb://127.0.0.1/test';
mongoose.connect(uri, function(req, res){
    console.log('mongodb connected');
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

// global variables for MongoDB model
global;
global.User = mongoose.model('users', {
    name: String,
    age: Number
});

module.exports = app;

var server = app.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + server.address().port);
});



[users.js]

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');


/* GET users listing. */
router.get('/', function(req, res, next){
	console.log(req.query);
	var myUser = new global.User({ name: req.query.name, age: req.query.age });
	myUser.save(function(err){
		console.log('Inserted');
		res.send(req.query.name + ' is inserted.');
	});
});

module.exports = router;



[웹 브라우저에서 쿼리 입력]

http://127.0.0.1:3000/users/?name=gchoi&age=38




[DB 확인]

> db.users.find().pretty()
{
	"_id" : ObjectId("5533bf12df8c09bc36783f3a"),
	"name" : "gchoi",
	"age" : 38,
	"__v" : 0
}


Comments