2017-02-08 66 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)); 
    }); 
}); 

注意!你应该将这个逻辑分成不同的文件以保持你的项目更容易维护。对于我来说,将所有内容放在一个文件中的唯一原因是为了消除复杂性。

相关问题