【问题标题】:Saving Data Into MongoDB (with using mongoose) When HTML Button Clicked单击 HTML 按钮时将数据保存到 MongoDB(使用 mongoose)
【发布时间】:2021-10-31 00:44:36
【问题描述】:

我正在制作一个基本的博客应用程序,我想在用户单击提交按钮时保存他们的数据。我正在使用 mongoose 在 MongoDB 中保存数据。我写了一些代码,但它不起作用。我是这个网站的新手,我正在努力学习。

我写了一些代码保存到数据库中:

const mongoose = require("mongoose");
const User = require("../models/user");

const db_URI = 'my db_uri in here, idk about security so i didn't write it'; 
const button = document.getElementById("submit-btn");

mongoose.connect(db_URI)

button.onclick = function() {
    var user = new User( { # I made this variable for just test
        name:"qwe",
        password: "123",
        email: "example@hotmail.com"
    }); 

    user.save()
};

此代码用于我的前端部分:

<!DOCTYPE html>
<html>
    <head>
        <title>SIGN UP HERE</title>

    </head>


    <body>
        <form method="POST">
            <div>
                <label id="name-lbl">Name: </label>
                <input type="text" name="nick" placeholder="Your nickname here">
            </div>
            <div>
                <label>E-mail: </label>
                <input type="text" name="email" placeholder="Your email here">
            </div>
            <div>  
                <label>Password: </label>
                <input type="password" name="pwd" placeholder="Your password here">
            </div>
            <div>
                <label>Confirm password: </label>
                <input type="password" name="pwd" placeholder="Confirm your password">
            </div>
            <button type="submit" id="submit-btn">Submit</button>
            
        </form>
        
        <script src="../database/db_processes.js"></script>
    </body>
</html>

【问题讨论】:

  • 前后端js都不一样;你需要实现一个像 express 这样的服务器来完成。
  • 好的。但是如何在不使用任何框架的情况下将用户的输入保存到数据库中呢?
  • 你不能;或使用火力;它对此有一些能力,

标签: javascript html mongodb mongoose


【解决方案1】:

你在这里混淆了一些东西。您的后端应用程序(您的第一个代码 sn-p)应该使用 Node.js 运行“服务器端”。你现在如何运行它?此外,第一个代码 sn-p 将无法访问前端组件,例如按钮和 div。

我的建议是通过本教程:https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs 学习架构的基础知识(客户端-服务器架构)。在第 3 部分中,他们介绍了如何与 Mongoose 建立联系。

【讨论】:

  • 那么我应该使用 Express 之类的框架来运行第一个代码并将其与前端连接吗?
  • @statist31 是的,本教程强调了这一点。您的浏览器将向您的后端(节点应用程序)发送网络请求。 Express 是帮助您处理请求的框架。
【解决方案2】:

更容易使用 REST URI 端点来保存、更新、查看、查找记录等。我已经使用 mongoose、node 和 express 完成了一个完整的教程,所以请随时查看:@987654321 @

【讨论】:

    猜你喜欢
    • 2012-05-07
    • 2017-07-27
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    相关资源
    最近更新 更多