user312456
user312456

Reputation: 102

Data not getting saved in the MongoDB from node.js

I want to create the rest api using node.js and mongodb I am entering all the details and trying it to store it in the mongodb database.

// call the packages we need
var express    = require('express');
var bodyParser = require('body-parser');
var app        = express();
var morgan     = require('morgan');

// configure app
app.use(morgan('dev')); // log requests to the console

// configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port     = process.env.PORT || 8080; // set our port

var mongoose   = require('mongoose');
// mongoose.connect('mongodb://node:[email protected]:27017/Iganiq8o'); // connect to our database
mongoose.connect('mongodb://localhost:27017');
var Bear     = require('./app/models/bear');
// create our router
var router = express.Router();

// middleware to use for all requests
router.use(function(req, res, next) {
    // do logging
    console.log('Something is happening.');
    next();
});

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')

    // create a bear (accessed at POST http://localhost:8080/bears)
    .post(function(req, res) {

        var bear = new Bear();      // create a new instance of the Bear model
        bear.name = req.body.name;  // set the bears name (comes from the request)
        bear.email= req.body.email;  // set the bears email(comes from the request)

        bear.save(function(err) {
            if (err)
                res.send(err);

            res.json({ message: 'Bear created!' });
        });


    })

    // get all the bears (accessed at GET http://localhost:8080/api/bears)
    .get(function(req, res) {
        Bear.find(function(err, bears) {
            if (err)
                res.send(err);

            res.json(bears);
        });
    });

// on routes that end in /bears/:bear_id
// ----------------------------------------------------
router.route('/bears/:bear_id')

    // get the bear with that id
    .get(function(req, res) {
        Bear.findById(req.params.bear_id, function(err, bear) {
            if (err)
                res.send(err);
            res.json(bear);
        });
    })

    // update the bear with this id
    .put(function(req, res) {
        Bear.findById(req.params.bear_id, function(err, bear) {

            if (err)
                res.send(err);

            bear.name = req.body.name;
            bear.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Bear updated!' });
            });

        });
    })

    // delete the bear with this id
    .delete(function(req, res) {
        Bear.remove({
            _id: req.params.bear_id
        }, function(err, bear) {
            if (err)
                res.send(err);

            res.json({ message: 'Successfully deleted' });
        });
    });
// REGISTER OUR ROUTES -------------------------------
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

The Model is given below:-

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var BearSchema   = new Schema({
    name: String, 
    email: String
});

module.exports = mongoose.model('Bear', BearSchema);

I am trying it to save the name and the email in the mongodb database but only _id is created instead of name, email.

Here is the result:-

[
{
    "_id": "567f1f92db24304013000001",
    "__v": 0
  },
  {
    "_id": "567f2765db24304013000002",
    "__v": 0
  }
]

Can anybody tell me why the data are not getting saved in the database.

Please kindly help.

Thanks in Advance.

Upvotes: 1

Views: 1497

Answers (1)

nenadg
nenadg

Reputation: 430

I think your POST request is not good, so I made this simple script to check it out:

var XHR = (function() {

  var _xhr = (function() {
    try {
      return new(this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
    } catch (e) {}
  })();

  return function(method, url, params, callback) {

    _xhr.onreadystatechange = function() {
      if (_xhr.readyState == 4) {
        var _response;

        try {
          _response = JSON.parse(_xhr.response);
        } catch (e) {
          _response = _xhr.responseText;
        }

        if (_xhr.status != 200) {
          // catch an error
          console.error('error', response);
        } else {

          if (callback) {

            callback(_response);
          } else {
            // deal with it
          }
        }
      }
    }

    if (!params) {
      params = JSON.stringify({});
    } else {
      params = JSON.stringify(params);
    }

    _xhr.open(method, url, true);

    // just json in this case
    _xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");
    _xhr.send(params);
  };
})();

fire it up in browser's console, like this

XHR('POST','api/bears', { name:'yogi', email:'[email protected]'}, function(){ console.log(arguments) });

and your record will be saved.

{ "_id" : ObjectId("567e875d068748ee5effb6e0"), "email" : "[email protected]" "name" : "yogi", "__v" : 0 }

Long story short - your code is okay, your POST is not.

Upvotes: 2

Related Questions