简体   繁体   中英

Cannot insert data from frontend Javascript to database using Mongoose

I am working on an Node.js-Express.js-Mongoose application. I want to accept user details (Name and Age) in an html form (EJS file), save into databse (using mongoose) display the added user details on the webpage . I am using AJAX for the same. The files used are :

userview.ejs (contains the Form) --> frontend.js (uses jquery) --> users.js (router file- calls the add() function defined in the userController) --> userController.js (attached below) --> userService.js (performs DB operations).

Check the image of how the list should look like. 用户表格

What actually happens is that a new user is created but the name isnt displayed.

空白条目

A peek into database shows that only IDs of the blank entries are added. Mongodb快照

FRONTEND.js

console.log('Frontend Reached');

$(document).ready(function() {

  var url = '/users/delete_user';
  var user_url = '/users/add_user';


  function load_users(e) {
    $.ajax({
      url: 'userview.ejs',
      dataType: 'text',
      type: 'post',
      ContentType: 'html',
      data: $('#user_form').serialize(), 
      success: function(data, textStatus, jQxhr) {
        console.log(data);
        $('#list').html(data);
        //$('#user_form').submit( load_users );
      },
      error: function(jqXhr, textStatus, errorThrown) {
        console.log(errorThrown);
      }
    });

    e.preventDefault();
  }

//ADDING A USER

  $(document).on('click', '.btn btn-success', function(e) {
    e.preventDefault();
    var user_name = $("#nameinput").val();
    var user_age = $("#ageinput").val();
    console.log(user_name);
    console.log(user_age);

    $.ajax({
      url: 'userview.ejs',
      dataType: 'text',
      type: 'post',
      ContentType: 'html',
      data: {
        'user_name': user_name,
        'user_age': user_age
      },
      success: function(data, textStatus, jQxhr) {
        console.log(data);
        load_users();
      },
      error: function(jqXhr, textStatus, errorThrown) {
        console.log(errorThrown);
      }
    });

    e.preventDefault();


  }); //onclick



}); //document ready

This is userController.js Console logging in this file shows that the record is undefined.

var User = require('../models/usermodel.js');
var userService = require('../services/userService');

var userController = {
  add: function(request, response) {
    var user_name = request.body.user_name;
    var user_age = request.body.user_age;
    console.log(user_name);   //SHOWS UNdEFINED
    var newUser = new User({
      name: user_name,
      age: user_age
    });
    console.log(newUser);
    //var userName = request.body.user_name;
    //var userAge = request.body.user_age;
    userService.add(newUser, function(err, added) {
      if (err != null) {
        response.send(500);
      } else {
        response.send(200);
      }
    });
  },

  delete: function(request, response) {

    var userId = request.body.user_id;
    userService.delete(userId, function(err, deleted) {
      if (err != null) {
        response.send(500);
      } else {
        response.send(200);
      }
    });
  }
};

module.exports = userController;

Send your data using JSON.stringify() , and specify the content-type to 'application/json' so your server will know to expect a JSON.

var data = {
    'user_name': user_name,
    'user_age': user_age
  },

$.ajax({
  url: 'userview.ejs',
  type: 'post',
  contentType: 'application/json',
  data: JSON.stringify(data), 
  success: function(data, textStatus, jQxhr) {
    console.log(data);
    load_users();
  },
  error: function(jqXhr, textStatus, errorThrown) {
    console.log(errorThrown);
  }
});

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