samedi 25 août 2018

Saving data in Mongodb using angularJS5

I am new to AngularJS5 and Mongodb. I am creating a signup page using AngularJS 5. There I created the database function as below. mongoDBCOnfig.js

const mongoServerLocation = "//localhost";
const mongoPort = "27017";
const dbName = "Test";

var connectionURL = 'mongodb://' + mongoServerLocation + ':' + mongoPort + '/' + dbName;
var mongoose = require('mongoose');

mongoose.connect(connectionURL);
var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
  console.log("Connected to DB succesfully");
});

module.exports = db;

Then I created the register.js file as below.

var express = require('express');

var router = express.Router();
var userInfo = require('../models/mongoModels/user');


/* POST; Save user Data. */
router.post('/', function (req, res, next) {
var newUser = new userInfo({
    firstName : req.body.firstName,
    secondName : req.body.secondName,

   });

   newUser.save(function (err, user) {
     if (err) return console.error(err);
     console.log("user");
   });

});

module.exports = router;

Following is my app.js file.

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser');

var user = require('./routes/user');
var userInfo = require('./routes/userInfo');
var register = require('./routes/register');
var app = express();


app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'false'}));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/#/pages/dashboard', express.static(path.join(__dirname, 'dist')));
app.use('/user', user);
app.use('/userInfo', userInfo);
app.use('/register', register);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

I have created my end point as '/register'. But when I enter details for register function it does not register them. My questions are, 1) Is my written code correct? 2) What are the possible errors in this kind of a problem?




Aucun commentaire:

Enregistrer un commentaire