2017-02-08 64 views
0

我試圖將數據插入到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)); 
}) 

我再開用MongoDB的連接,創造了「測試」收集成功...

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});」 但這顯然沒有工作,因爲沒有「請求」。我如何使輸入全球 ,所以我可以簡單地插入它們?

回答

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)); 
    }); 
}); 

注意!你應該將這個邏輯分成不同的文件以保持你的項目更容易維護。對於我來說,將所有內容放在一個文件中的唯一原因是爲了消除複雜性。

相關問題