简体   繁体   中英

insert user data into mongodb database

I am trying to insert data into a mongodb database.

I am able to submit user data and display it with...

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

I then opened a connection with mongodb and created a "test" collection successfully...

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

I tried "collection.insert({name:req.query.firstName});" but this obviously didn't work because no "req". How do I make the inputs global so I can simply insert them?

You don't have to do this within the database connection callback. Simply connect to your database in the process and then invoke the models.

//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! You should split this logic out in different files to keep your project easier to maintain. The only reason for me to have it all in one file is to remove complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM