我正在尝试将数据插入到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的连接并创建了一个" test"收集成功......
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 :(得分: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!您应该将此逻辑拆分为不同的文件,以使您的项目更易于维护。我将它全部放在一个文件中的唯一原因是消除复杂性。