简体   繁体   English

无法使用Mongoose将数据从前端Javascript插入数据库

[英]Cannot insert data from frontend Javascript to database using Mongoose

I am working on an Node.js-Express.js-Mongoose application. 我正在开发Node.js-Express.js-Mongoose应用程序。 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 . 我想以html格式(EJS文件)接受用户详细信息(名称和年龄),保存到数据库(使用猫鼬)中,在网页上显示添加的用户详细信息。 I am using AJAX for the same. 我同样使用AJAX。 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). userview.ejs (包含表单)-> frontend.js (使用jquery)-> users.js (路由器文件-调用userController中定义的add()函数)-> userController.js (如下所示)- -> userService.js (执行数据库操作)。

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. 窥数据库显示,仅添加了空白条目的ID。 Mongodb快照

FRONTEND.js 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. 这是userController.js在此文件中的控制台日志,显示该记录未定义。

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. 使用JSON.stringify()发送数据,并将内容类型指定为'application / json',这样您的服务器就会知道需要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);
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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