2017-02-08 19 views
0

mongodbデータベースにデータを挿入しようとしています。mongodbデータベースにユーザデータを挿入

私は、その後のMongoDBとの接続をオープンし、成功した「テスト」のコレクションを作成したユーザデータを提出して...

app.get('/process_get', function (req, res) { 
    response = { 
     first_name:req.query.firstName, 
     last_name:req.query.lastName, 
     username:req.query.userName, 
     password:req.query.password, 
     email:req.query.email 
    }; 
    console.log(response); 
    res.end(JSON.stringify(response)); 
}) 

でそれを表示することができるよ...

MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) { 
    if(err) { return console.dir(err); } 
    if(!err) { console.log("MongoDB server is connected!") } 

    var collection = db.collection('test'); 
}) 

私は "collection.insert({name:req.query.firstName});" しかし、これは "req"がないので明らかに機能しませんでした。入力をグローバルにするにはどうすればいいですか?

答えて

0

データベース接続コールバック内でこれを行う必要はありません。プロセスでデータベースに接続し、モデルを呼び出すだけです。

//Setup Server and connect to mongoDB 
var app = require('express')(); 
var mongoose = require('mongoose'); 
mongoose.Promise = require('bluebird'); 
mongoose.connect('mongodb://localhost:27017/exampleDb'); 

//Create the model 
var testSchema = mongoose.Schema({ 
    .. 
}); 
var Test = mongoose.model('test', testSchema); 

//Now use the model to save the object in the route controller 
app.get('/process_get', function (req, res) { 
    response = { 
    .. //build the object based on some input or pas req.body directly 
    }; 
    console.log(response); 
    new Test(response).save().then(function(result) { 
    res.end(JSON.stringify(result)); 
    }); 
}); 

NB!このロジックを別のファイルに分割して、プロジェクトの保守を容易にする必要があります。私が1つのファイルにまとめた唯一の理由は、複雑さを取り除くことです。