Search code examples
jqueryajaxnode.jsput

PUT route with Node.JS


I am new here and I have a problem, I hope you can help me :).

I have the following AJAX in my client side that sends the data to update the database:

$.ajax({
 type: 'PUT',
 url: host + '/database',
 data {
  name: 'MisterX',
  email: 'mister.x@gmail.com
 },
 sucess:function(sucess) {
  alert('sucess');
 },
 err:function(err) {
  console.log(err);
 }
});

Them, in my routes file i have:

app.put('/database', function(req, res) {
        require('data', function (data){
            var database = data;

            database.save(function (err) {
                if(err) {
                    console.log('err', err);
                }
                res.status(200).json('ok');
                console.log('Database updated');
            });
        });
    });

This put route was completely done in theory, I do not know exactly how to take the data and updates them in my database

My schema:

var databaseSchema = mongoose.Schema({
        name: String,
        email: String,
    });

If someone can give me a direction, I appreciate it.

Thanks.


Solution

  • Schema file databaseScheme.js

    ....
    var databaseSchema = mongoose.Schema({
        nome: String,
        email: String,
    });
    ...
    

    route

    /*
     * body-parser is a piece of express middleware that 
     *   reads a form's input and stores it as a javascript
     *   object accessible through `req.body` 
     *
     * 'body-parser' must be installed (via `npm install --save body-parser`)
     * For more info see: https://github.com/expressjs/body-parser
     */
    var bodyParser = require('body-parser');
    var app = express();
    // instruct the app to use the `bodyParser()` middleware for all routes
    app.use(bodyParser());
    
    var Database = require(. / databaseScheme);
    ...
    ...
    // As explained above, usage of 'body-parser' means
    // that `req.body` will be filled in with the form elements
    // Adds a new document
    app.post('/database', function(req, res) {
        var database = new Database();
        database.name = request.body.name;
        database.email = request.body.email;
        database.save(function(err) {
            if (err) {
                console.log('err', err);
            }
            res.status(200).json('ok');
            console.log('Database updated');
        });
    });
    
    // Update a document
    app.put('/database/:id', function(req, res) {
        Database.findById(req.param('id'), function(err, database){
            database.name = request.body.user;
            database.email = request.body.user;
            database.save(function(err) {
                 if (err) {
                    console.log('err', err);
                 }
                 res.status(200).json('ok');
                 console.log('Database updated');
           });
      });
    });